0

I have problems with NSDate to NSString conversion, I have the following code in a method

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[formatter setTimeZone:timeZone];
[formatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'zzz'"];
return [formatter stringFromDate:date];

If I´m not mistaken this should return a String like

"2016-01-15T22:45:40.GMT"

But the resulting string depends on the device configuration, meaning if the device shows the date as 24 hour then i get the result above, on the other hand if the device is configured to show the house as A.M. P.M. then I get

"2016-01-15T10:46:50 p.m..GMT"
Francisco Medina
  • 363
  • 3
  • 11
  • 4
    You probably need to set the locale: see [this question](http://stackoverflow.com/q/6613110/3985749) for details. – pbasdf Jan 15 '16 at 23:10
  • Above answer is nice because you can reuse it easier. But if you don't want to create category, you could set formatter's locale like this formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; – thanyaj Jan 15 '16 at 23:39
  • FYI - you don't need to escape all of the punctuation. Your format can be `yyyy-MM-dd'T'HH:mm:ss.zzz`. Note you do need to escape the `T`. – rmaddy Jan 16 '16 at 00:04

1 Answers1

1

From the documentation:

Although in principle a format string specifies a fixed format, by default NSDateFormatter still takes the user’s preferences (including the locale setting) into account. You must consider the following points when using format strings:

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.

I think you'll have to consider using your own formatting method if you want the result to have a fixed format, regardless of user settings.

Actually, from this answer (as pointed out by pbasdf), it appears that you can circumvent this by simply setting the locale:

NSLocale* en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocale:en_US_POSIX];
Community
  • 1
  • 1
Hamish
  • 78,605
  • 19
  • 187
  • 280