NSDateFormatter will not parse string with timezone that includes colon

泄露秘密 提交于 2019-12-01 14:21:35

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

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];

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!