finneycanhelp
finneycanhelp

Reputation: 9248

Why Does NSDateFormatter return a nil on iOS 7

When runDate value is @"Fri, 01 Nov 2013 08:47:33 GMT-0500", I get nil on iOS 7 iPhone simulator, but it's ok on iOS 6 iPhone simulator

        NSString *runDate = [reportDictionary objectForKey:@"runDate"];

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
        formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss ZZZ";

        NSDate *actualRunDate = [formatter dateFromString:runDate];

I end up with an actualRunDate of nil on iOS 7 simulator but not on iOS 6.1

How can I get it to work on iOS 7?

Upvotes: 1

Views: 679

Answers (2)

Jasper Blues
Jasper Blues

Reputation: 28786

Ah, I think I see what is happening.

According to the docs you can specify three 'ZZZ' characters for dates in the format:

Fri, 01 Nov 2013 08:47:33 -0500

And you can specify four 'ZZZZ' characters for dates in the format:

Fri, 01 Nov 2013 08:47:33 GMT-05:00

Note the colon character in between the GMT hours and minutes!

Therefore, I think the solution (if you can't change the date format you're getting), is to set the formatter as follows:

formatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss 'GMT'ZZZ";

. . this will skip over the 'GMT' part, treating it as a date in the 'ZZZ' format.

As pointed out in the comment by @rmaddy, this solution assumes that all dates have the letters 'GMT' in the timezone. If they're expressed in relation to some other timezone, then you'll have to fix the format of the date you're being supplied, or perhaps parse the string manually first (extract those characters with a regular expression or something), if you simply can't do that.

The ideal solution is to fix the date format being supplied to the client, however according to the principles of contract-first development we should be as tolerant as we can (assuming this date that you need to parse is being consumed from a remote service with many down-stream subscribers, all of which might have to change if the format was corrected).

Upvotes: 3

Sorin Cioban
Sorin Cioban

Reputation: 2225

If you remove GMT from the string you're trying to parse and have it look like this

@"Fri, 01 Nov 2013 08:47:33 -0500"

the date returned will be correct. Everything else seems to be fine.

Upvotes: 1

Related Questions