简体   繁体   中英

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

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.

时区说明符为'z',因此您的字符串应为:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM