NSDateFormatter 将不会解析包含冒号的时区的字符串
我正在尝试将 @"Fri, 26 Aug 2011 10:51:00 +02:00"
转换为 NSDate
:
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:dateString];
我得到 nil
结果;我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 getObjectValue:forString:range:error: 方法来解析时区中包含冒号的日期:
You can use the getObjectValue:forString:range:error: method to parse dates that have the colon in the timezone:
时区
(+02:00)
中的冒号是问题所在。根据 Unicode 标准 #35,1..3 大写 Z 模式表示 RFC 822 时区。 RFC 822 时区表示与 GMT(或 UTC)的偏移量,并具有以下格式:如您所见,时区的小时和分钟之间没有冒号。因此,时区应为
+0200
。最合适的解决方案是首先生成一个兼容 unicode 的日期字符串,但如果您坚持使用这种格式,则可能需要在将日期字符串传递给
NSDateFormatter
之前对其进行预处理。例如,快速修复方法是使用 stringByReplacingOccurrencesOfString 删除时区中的冒号:
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: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:不需要字符串操作。将格式字符串更改为:
我测试了它,它可以很好地解析您给出的日期。当我使用 [NSDate description] 打印日期时,我得到 2011-08-26 08:51:00 +0000,这相当于字符串中给出的日期。
No string manipulation required. Change your format string to:
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.
是的,这是一个常见问题。许多服务器在时区中生成带有冒号的日期,并且 NSDateFormatter 无法(据我所知)被说服接受它。解决方案是按照建议以某种方式切除冒号。
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.