Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter dateFromString returns nil

Here is my code :

NSString *_date = @"Tue, 23 Nov 2010 16:14:14 +0000";
NSDateFormatter *parser = [[NSDateFormatter alloc] init];
[parser setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss '+0000'"];
[parser setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSDate *date = [parser dateFromString:_date];

This doesn't run : 'date' is set to 'nil'. I tried with

[parser setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];

With no more success...

Do you have any idea ?

Thanks in advance

like image 864
Harkonnen Avatar asked Nov 23 '10 16:11

Harkonnen


2 Answers

Add this line:

NSDateFormatter *parser = [[NSDateFormatter alloc] init];
[parser setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];

and it will work. By default, NSDateFormatter uses the system's current locale, which can vary depending on the current user's preferences. The date string above (@"Tue, 23 Nov 2010 16:14:14 +0000") contains English words ("Tue", "Sep") that would potentially not be recognized by the date formatter if the locale would be set to anything other than English.

Moreover, users from non-western cultures might use locales that use a different calendar than the Gregorian calendar that's used in the western world. If you did not explicitly set the locale, the date formatter might be able to parse the date but the resulting NSDate would represent a whole other point in time.

The locale identifier @"en_US_POSIX" is meant for this purpose. It is guaranteed to not change even if the @"en_US" locale should someday change its default settings.

like image 172
Ole Begemann Avatar answered Nov 01 '22 23:11

Ole Begemann


The timezone specifier is 'z', so your string should be:

[parser setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z"];
like image 39
Denis Hennessy Avatar answered Nov 01 '22 23:11

Denis Hennessy