Question

I'm stuck on a stupid problem. According to Apple, setting the locale property on a NSDateFormatter instance would override some settings like for example whether the user prefers the 12 or the 24 hour format. A newly created NSDateFormatter instance is initialized with the current locale. WWDC 2011 Session 117 talks about this 12/24 hour problem @ 54:00. Here is the code I'm using:

NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];
NSLog(@"%@",[formatter stringFromDate:date]);

According to Apple's docs and the WWDC session this should output the current time with the user's preferred locale, even if the format is explicitly set to HH:mm. But for some reason, I always get the 24 hour representation. I've also tried to set the locale specifically to [NSLocale autoupdatingCurrentLocale], [NSLocale currentLocale] and a bunch of different country locales. Same result. Any ideas?

Was it helpful?

Solution

Try setting timeStyle instead of dateFormat:

formatter.timeStyle = NSDateFormatterShortStyle;
formatter.dateStyle = NSDateFormatterNoStyle;

OTHER TIPS

If your prefer your own format (for example, you don't want to display years, which is included in every system provided date style), you can use j in a format template like this:

NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setLocalizedDateFormatFromTemplate:@"jjmm"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top