Search code examples
iphoneobjective-cxcodensdatensdateformatter

How to display time in 12 hour format in Objective-C?


I was working on an iPhone application, and I need to display the time in a label. So I wrote the follow:

NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm a"];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
timeLabel.text = formattedDateString;**

It displays time in label but in 24H format.

  • Example: 15.00 PM instead of 3.00 PM

I want to display time in 12h format, i.e. 3.00 PM

What should I do?

Thanks in advance.


Solution

  • [dateFormatter setDateFormat:@"hh:mm a"];

    Note the lower case h's.