开发者

NSDateFormatter dateFromString returns nil

开发者 https://www.devze.com 2023-01-26 07:20 出处:网络
Here is my code : NSString *_date = @\"Tue, 23 Nov 2010 16:14:14 +0000\"; NSDateFormatter *parser = [[NSDateFormatter alloc] init];

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];

开发者_C百科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.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号