NSDateFormatter- stringFromDate not returning AM/PM

天大地大妈咪最大 提交于 2019-11-30 13:28:45

Check your device settings for 24 hour time. If it is on, turn it off.

Your code is perfectly fine. I am getting output as shown below : Today's Time: 04:31:58 PM

If you don't want to show seconds use this code :

[formatter setDateFormat:@"hh:mm a"];

HH : 24 hour format

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:locale];
[formatter setDateFormat:@"HH:mm a"];

output

 Today's Time: 16:42 PM

hh : 12 hour format

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:locale];
[formatter setDateFormat:@"hh:mm a"];

output

 Today's Time: 04:43 PM

Change the time format of your device time to 12 hour format instead of 24 hour format. You can not get am pm in 24 hour time format.

Today's Time: 15:46:43

Try This

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a"];
    [dateFormatter setLocale:[[NSLocale alloc]  initWithLocaleIdentifier:@"en_US_POSIX"]];
    NSString *stringFromTime = [dateFormatter stringFromDate:[NSDate date]];

Try

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"hh:mm a"];
NSLog(@"Today's Time: %@", [formatter stringFromDate:[NSDate date]]);

You can easily convert Time in 24 hours format .

Try this Code it is working fine for me .

        func convertTime(_ date : String) -> String{
             let dateAsString = date
             let dateFormatter = DateFormatter()
             dateFormatter.dateFormat = "h:mm:ss " // "h:mm:ss a"
             date = dateFormatter.date(from: dateAsString)

             dateFormatter.dateFormat = "HH:mm a"
             let date24 = dateFormatter.string(from: date!)
              print(date24)
              return date24
          }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!