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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With