0

I am trying to parse data from EXIF date to NSDate. Here is a sample date string taken from an image file:

2013:10:15 19:19:31

It is in year:month:day 24hour:minute:second format. I am using the following code to parse this:

NSDateFormatter *formatter = [[NSDateFormatter alloc] initWithDateFormat:@"yyyy:MM:dd HH:mm:ss" allowNaturalLanguage:YES];
formatter.formatterBehavior = NSDateFormatterBehavior10_4;
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSDate *date = [formatter dateFromString:dt];

If I don't set the formatter behavior it complains about trying a locale identifier of 10.4 on an 10.0 formatter. (I'm on Mavericks, I think it's a new issue on Mavericks) Anyway I've tried combinations of not setting locale at all, setting locale to en_US_POSIX instead of just en_US, setting a timezone for formatter, changing yyyy to YYYY in date format, and allowNaturalLanguage to NO, however, dateFromString always returns nil. My app is running on OS X Mavericks, my system's language is English, and my region is set to Turkey if it matters. I want my app to be English-only, independent of users' region (including the date formats). I've seen this question: Parsing EXIF date string to NSDate but even I try the exact steps, formatter returns nil for dateFromString. What is wrong with the date formatter?

Community
  • 1
  • 1
Can Poyrazoğlu
  • 33,241
  • 48
  • 191
  • 389
  • it worked. weird. it looks like a bug in the formatter. could you please post this as an answer so I can accept it, with any possible explanation for this weird behavior of date formatter (if any)? – Can Poyrazoğlu Nov 04 '13 at 19:00
  • 1
    It looks like you were doing everything correctly -- no explanation, other that gremlins. – Hot Licks Nov 04 '13 at 19:01

1 Answers1

2

It seems to be a problem of the initWithDateFormat initializer. According to the documentation, it creates a formatter that uses the "OS X v10.0 formatting behavior", but I have no idea what that is. And setting the behavior to NSDateFormatterBehavior10_4 explicitly seems also not to help.

Using

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"];
NSDate *date = [formatter dateFromString:@"2013:10:15 19:19:31"];

produces the expected result.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382