NSDateFormatter-stringFromDate does not return AM / PM

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

The above code just gives the following Today Time: 15:46:43 output Today Time: 15:46:43 I want the result to be Today Time: 3:46 PM . I was busy a lot and I did not find a way to show AM / PM. It would be really helpful if someone could help me find a way out. I am using Xcode 6.3 and my device has iOS 8.3 installed in it.

+7
datetime ios nsdate date-format nsdateformatter
source share
5 answers

Check your device’s settings for 24 hours. If it is on, turn it off.

Your code is ok. I get the output as below: Today Time: 04:31:58 PM

If you do not want to show seconds, use this code:

 [formatter setDateFormat:@"hh:mm a"]; 
+13
source share

HH: 24 hours format

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

Exit

  Today 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"]; 

Exit

  Today Time: 04:43 PM 
+7
source share

Change the time format of your device to 12-hour format instead of 24-hour format . You cannot get pm in 24 hours format.

Today Time: 15 : 46: 43

+1
source share

try it

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

Try

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

All Articles