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.
The timezone specifier is 'z', so your string should be:
[parser setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With