1
votes

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.

1
What exactly is your problem? You should set the locale of the date formatter to [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]Fabian Kreiser
Yes, please specify what the problem is. And note what Fabian says about using en_US_POSIX -- there's a "feature" of iOS that time formatting gets screwed up if the 12/24 switch in Settings is in contradiction to the locale.Hot Licks
I have clarified what the problem is. Tested the solution as presented by @FabianKreiser and it works. However I do not understand why this method works for some date parsing and do not work for other. I have used this code successfully. Can someone please explain why?Johan Karlsson
@HotLicks Is there a simple workaround for this 'feature'?Johan Karlsson
Yes. As I indicated, you should do what Fabian suggested. You can see this thread for a category you can create to encapsulate setting the locale. Also see that thread for several references explaining Apple's problem.Hot Licks

1 Answers

2
votes

NSDateFormatter is 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_POSIX locale identifier to get a date formatter back that doesn't respect locale settings and always uses the same behavior.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

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, ...

    NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"dd MMMM yyyy" options:0 locale:[NSLocale currentLocale]];
    [dateFormatter setDateFormat:dateFormat];