问题
I'm parsing a large number of internet dates. First I try a formatter with en_US_POSIX
locale, then with en_GB
. The code looks more or less like this:
{
NSDate *date = [dateString dateWithDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z (zzz)" localeIdentifier:@"en_US_POSIX"];
if (date) return date;
date = [dateString dateWithDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z (zzz)" localeIdentifier:@"en_GB"];
return date;
}
- (NSDate*) dateWithDateFormat:(NSString*)dateFormat localeIdentifier:(NSString*)localeIdentifier
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
formatter.dateFormat = dateFormat;
[formatter dateFromString:self];
}
However, date strings with the following time zones fail to parse:
Mon, 16 Jul 2012 12:08:17 +0100 (GMTUK)
Thu, 6 Sep 2012 13:00:06 +0900 (KST)
Wed, 3 Nov 2010 10:12:15 +0100 (Hora est�ndar romance)
Wed, 14 Sep 2011 14:37:35 +0100 (IST)
Wed, 2 May 2012 09:41:06 +0200 (MEST)
Sun, 31 Oct 2010 12:53:06 +0800 (SGT)
Thu, 19 Jan 2012 08:34:44 -0300 (UYT)
What am I doing wrong?
Should I pre-process the strings to remove the time zone parenthesis in these cases only?
回答1:
NSDate
can store a point in time without timezone information. It's up to your software to know whether a specific NSDate
instance stores the point in time in UTC or in the local time zone. In most cases, you want to use UTC dates.
Because of that, it's important to handle time zone differences when parsing the dates. But it's not possible to remember the time zone the dates was originally in (at least not with an NSDate
instance only).
So I would recommend that you cut off the time zone in parenthesis and just parse the numerical time zone offset before it. That way, you can convert all strings into an NSDate
instance in UTC and you shouldn't have any problems parsing the strings.
And shouldn't the date fromat be (i.e. uppercase Z for a numeric time zone offset)?
@"EEE, dd MMM yyyy HH:mm:ss ZZZ"
来源:https://stackoverflow.com/questions/14058298/how-to-parse-these-time-zones-with-nsdateformatter