2

I've been using the following NSDateFormatter code for formatting my date strings with the following output: '2013-02-18 03:23:32.928000 +0000'

This has been consistently working until a user with a European iPhone was added where the output changed to: '2013-02-18 02:00:40 AM.118000 +0000'

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];    
[dateFormatter setTimeZone:timeZone];    
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSSSSS Z"];

Any hint on why the formatter isn't working consistently?

x89a10
  • 681
  • 1
  • 8
  • 23
  • 1
    It's because the user has set the 12/24 hour mode of his phone in conflict with his locale's 12/24 default. You must set the locale of your NSDateFormater to a version that doesn't behave in this flaky manner -- generally en_US_POSIX. – Hot Licks Feb 18 '13 at 03:53
  • Thanks for pointing this out as a duplicate question. I still think there is a value in keeping this question alive since the title of the other question is not as direct to the point as this one. In other words when I experienced this issue, I didn't think that the answer to my question is given within a question titled: "What is the best way to deal with the NSDateFormatter locale “feature”?". Please let me know how I should edit and proceed with this question to make it mostly useful for everyone. Thanks. – x89a10 Feb 18 '13 at 23:26

1 Answers1

5

In the iOS documentation, there is this line:

In iOS, the user can override the default AM/PM versus 24-hour time setting. This may cause NSDateFormatter to rewrite the format string you set.

That's why you're getting the AM/PM as opposed to the 24-hour format.

You can fix this by overriding the locale of your NSDateFormatter.

[dateFormatter setLocale:
 [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]] autorelease];
tom
  • 18,953
  • 4
  • 35
  • 35
  • I suspect that version of init is in a category you're using -- it's undocumented. See [this answer](http://stackoverflow.com/a/6735644/581994) for a slightly different category. – Hot Licks Feb 18 '13 at 03:50