I have problem using the NSDateFormatter to parse a date string. I have implemented the method method below as an NSDate category. The input is the following date string Thu, 22 Dec 2011 16:03:39 +0100 and using the following pattern for parsing EEE, dd MMM yyyy HH:mm:ss ZZZ
The problem is that the method returns nil
+(NSDate*) dateFromString:(NSString*)dateString pattern:(NSString*)pattern
{
NSDateFormatter *dateParser = [[NSDateFormatter alloc] init];
[dateParser setDateFormat:pattern];
NSDate *parsedDate = [dateParser dateFromString:dateString];
return parsedDate;
}
I have looked on Stackoverflow and elsewhere on the Internet, but not found a solution to this problem.
NSDateFormatteris quite smart about region settings like 12/24 hour display, month and weekday names, etc.If you initialize a date formatter it always uses the current locale, you can set the locale manually, though. You can use the
en_US_POSIXlocale identifier to get a date formatter back that doesn’t respect locale settings and always uses the same behavior.This is handy (and required, actually) if you need to parse date strings returned from a server for example.
If you want to display date strings in your app, you should never use the
-setDateFormat:method directly, btw. Use+dateFormatFromTemplate:options:locale:method to get the correct date format.In some languages the month is written before the day, …