iPhone NSDateFormatter 时区转换
我正在尝试创建一个格式化程序,将显示的日期格式转换为 NSDate 对象:
NSString *dateStr = @"2010-06-21T19:00:00-05:00";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [dateFormat dateFromString:dateStr];
问题是时区 -05:00,无法使用上面的格式正确解析。有什么建议吗?
I am trying to create a formatter that will convert the date format shown to an NSDate object:
NSString *dateStr = @"2010-06-21T19:00:00-05:00";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [dateFormat dateFromString:dateStr];
The issue is the timezone -05:00, which is not parsed properly with the format above. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要处理带有冒号的时区,只需使用 5 个“Z”即可。这是一种非常常见的日期格式,即 ISO-8601 格式。这仅适用于 iOS 6.x+
To process the time zone with the colon in it, you just need to use 5 'Z's. This is a pretty common date format, the ISO-8601 format. This will only work on iOS 6.x+
老实说,您只需在通过格式化程序运行源数据之前更改源数据(删除冒号)即可。您的原始日期字符串是非标准的,任何时区格式字符串都无法在其上正常工作。
您可以在 unicode.org 上查看有效输入。
ZZZ 例如“-0500”
ZZZZ 例如“GMT-05:00”
对于“-05:00”没有任何内容
Honestly, you'll just have to change the source data (removing the colon) before running it through the formatter. Your original date string is non-standard and none of the time zone format strings will work properly on it.
You can see the valid inputs on unicode.org.
ZZZ e.g. "-0500"
ZZZZ e.g. "GMT-05:00"
Nothing for "-05:00"
也许我错过了一些东西,但
ZZ
对我有用。我用过:
用于
May be I missed something but
ZZ
worked for me.I used:
for
这是我从 Sinatra ActiveRecord 后端获得的默认时间格式。这是我的解决方案。
This is the default time format I got from a Sinatra ActiveRecord backend. Here is my solution.
这是唯一对我有用的解决方案:
This is the only solution that worked for me:
5 ZZZZZ - 这是我用 GMT 到 BST 的一些示例编写的类别
https://github.com/clearbrian/NSDateFormatter_ISO_8601< /a>
5 ZZZZZ - heres a category I wrote with some sample of GMT to BST
https://github.com/clearbrian/NSDateFormatter_ISO_8601