10

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?

Ecuador
  • 1,014
  • 9
  • 26
  • what if you removed [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; and tried getting the hour value? – Sam B Mar 31 '15 at 18:58
  • Ok, I researched it more. That line doesn't affect it. The problem is when you have selected a region like UK or France that defaults to 24h format but you disable "24-hour time" in the settings and then do not set the locale for dateFormatter. Simple, huh? Choose UK, disable 24-hour time, "HH" breaks. Nice. – Ecuador Mar 31 '15 at 20:12
  • You are right, it is a known problem that I had not found in my search. Apple does not want to fix it either... – Ecuador Mar 31 '15 at 22:02

1 Answers1

17

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.

Ecuador
  • 1,014
  • 9
  • 26