2

I had a weird issue today, I have the following code:

#define kApiDateFormat @"MM/dd/yyyy HH:mm:ss a"

...
+ (NSDate*)dateWithApiFormatString:(NSString*)dateString {

  NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
  [dateFormat setDateFormat:kApiDateFormat];
  return [dateFormat dateFromString:dateString];

}

The date i'm trying to format is 12/29/2014 12:00:00 AM and my device's locale is es_CL, searching on the internet I've found a solution, I needed to set the locale of the dateFormatter to en_US like this:

[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

So my question is the following... WHY?, I couldn't find any information explaining why I couldn't parse the date string to a date using my device's locale.

Thanks

Community
  • 1
  • 1
Fantini
  • 2,067
  • 21
  • 32
  • 2
    `"AM"` and `"PM"` are not necessarily represented the same in every locale. – Ian MacDonald Jan 21 '15 at 19:53
  • 2
    [Documentation](https://developer.apple.com/library/ios/qa/qa1480/_index.html). Read it all, a short quote only for reference: "On iOS, the user can override the default AM/PM versus 24-hour time setting (via Settings > General > Date & Time > 24-Hour Time), which causes NSDateFormatter to rewrite the format string you set, which can cause your time parsing to fail." – A-Live Jan 21 '15 at 19:54
  • 1
    See this thread: http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature – Hot Licks Jan 21 '15 at 20:16

0 Answers0