Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter "HH" returning am/pm on iOS 8 device [duplicate]

I am stumped right now. I have been happily using NSDateFormatter with no problems, but today I noticed that one of my apps is giving me crazy results on an iPhone 6 plus device with iOS 8.1.3 - while it seems to be fine on other devices/simulator. Looking into it there is this code:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; 
[dateFormatter setDateFormat:@"HH"];
NSInteger hour= [[dateFormatter stringFromDate:datetime] integerValue];

This results (on the device) to 0-12 hour notation, because for a reason that is beyond me, if I print [dateFormatter stringFromDate:datetime] at that point I get "4 pm"!

What am I missing?

like image 958
Ecuador Avatar asked Mar 31 '15 16:03

Ecuador


1 Answers

Edited: To see the problem, in your phone settings select a region that defaults to a 24-hour time, for example "United Kingdom" or "France". Then, disable the "24 hour time" from the settings. Now if you create an NSDateFormatter without setting its locale, "HH" will not work. To circumvent this problem, set the locale (even to the same one the phone is at that moment) e.g. for the above code we could add:

dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

Any locale will work, even en_GB. This is obviously a bug, and not some sort of strange representation of the unicode standard, because if you have set a region that defaults to 12 hour time, the "24 hour time" slider does not affect how "HH" works, while if you are on a region that defaults to 24 hour time, then that slider in the settings will affect how your code works.

like image 119
Ecuador Avatar answered Oct 11 '22 15:10

Ecuador