开发者

NSDateFormatter will not parse string with timezone that includes colon

I'm trying to transform @"Fri, 26 Aug 2011 10:51:00 +02:00" into an NSDate:

[dateFormatter setDateFormat:@"EEE, d开发者_运维技巧d MMM yyyy HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:dateString];

I get nil as a result; what am I doing wrong?


You can use the getObjectValue:forString:range:error: method to parse dates that have the colon in the timezone:

// test date formatting
NSString *dateString = @"2012-04-11T18:34:19+00:00";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
NSDate *date;
NSError *error;
[formatter getObjectValue:&date forString:dateString range:nil error:&error];


The colon in the timezone (+02:00) is the issue. According to the Unicode Standard #35, 1..3 capital Z pattern denotes a RFC 822 time zone. RFC 822 time zones represent the offset from GMT (or UTC) and have the following format:

zone             =  "UT"  / "GMT"                ; Universal Time
                 ...
                 ...
                 / ( ("+" / "-") 4DIGIT )        ; Local differential
                                                 ;  hours+min. (HHMM)

As you can see, there is no colon between hours and minutes of the time zone. Therefore, the time zone should be +0200.

The most proper solution would be to generate a unicode compliant date string in the first place, but if you are stuck with this format, you may need to preprocess the date string before you pass it to NSDateFormatter.

For example, a quick fix would be using stringByReplacingOccurrencesOfString to get rid of the colon in the time zone:

// dateString --> Fri, 26 Aug 2011 10:51:00 +02:00
dateString = [dateString stringByReplacingOccurrencesOfString:@":" 
                                                   withString:@"" 
                                                      options:0
                                                        range:NSMakeRange(25, [dateString length] - 25)];
// dateString --> Fri, 26 Aug 2011 10:51:00 +0200
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:dateString];
// date --> 2011-08-26 08:51:00 +0000


No string manipulation required. Change your format string to:

[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z:00"];

I tested it and it parses the date you give just fine. When I print the date using [NSDate description], I get 2011-08-26 08:51:00 +0000, which is equivalent to the date given in the string.


Yeah, this is a common problem. A number of servers produce the date with the colon in the timezone, and NSDateFormatter can't (to my knowledge) be convinced to accept it. The solution is to cut out the colon somehow, as suggested.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜