NSDateFormatter不会解析包含冒号的时区的字符串 [英] NSDateFormatter will not parse string with timezone that includes colon
问题描述
我试图将 @转换成
NSDate code>:
[dateFormatter setDateFormat:@EEE,dd MMM yyyy HH:mm:ss Z];
NSDate * date = [dateFormatter dateFromString:dateString];
我得到 nil
c>(+ 02:00) code>是问题。根据 Unicode标准#35 ,1..3大写Z模式表示 RFC 822时区。 RFC 822时区表示从GMT(或UTC)的偏移,并具有以下格式:
zone =UT格林威治标准时间 ;世界时
...
...
/((+/ - )4DIGIT);本地差异
;小时+分钟。 (HHMM)
正如您所看到的,时区的小时和分钟之间没有冒号。因此,时区应该 +0200
。
最合适的解决方案是生成符合Unicode的日期字符串,但如果您仍然使用此格式,您可能需要预处理日期字符串,然后将其传递给 NSDateFormatter
。
例如,快速修复将使用 stringByReplacingOccurrencesOfString
来摆脱时区中的冒号:
// dateString - >周五,26 Aug 2011 10:51:00 +02:00
dateString = [dateString stringByReplacingOccurrencesOfString:@:
withString:@
选项:0
范围: 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
I'm trying to transform @"Fri, 26 Aug 2011 10:51:00 +02:00"
into an NSDate
:
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:dateString];
I get nil
as a result; what am I doing wrong?
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
这篇关于NSDateFormatter不会解析包含冒号的时区的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!