将字符串转换为 NSDate 对象
我从网络服务获取字符串“2011-09-24T00:30:00.000-07:00”。 我不知道这种格式是什么,想在 Objective-C 中转换为日期对象。
所以任何人都知道如何将此字符串转换为日期。
非常感谢
I am getting string "2011-09-24T00:30:00.000-07:00" from webservice.
I don't know the what is this format and want to convert in date object in objective-c.
So any know how to convert this string to date.
Thank you very much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从这种格式获取日期/时间存在一个小问题,即时区中的“:”,需要将其删除,Apple 不处理这种情况,也不是正确的 UTS 格式。下面是一个示例:
NSLog 输出:
date: 2011-09-24 07:30:00 +0000
作为显示刚刚创建的日期的测试:
NSLog 输出:
date: 2011-09- 24T03:30:00.100-0400
请注意,时间和时区已通过 NSLog 转换为我的本地时区,同时考虑到这两个更改日期/时间与原始日期/时间相同。
There is a small problem obtaining the date/time from this format, the ':' in the timezone, that will need to be removed, Apple does not handle this case nor it is a proper UTS format. Here is an example:
NSLog output:
date: 2011-09-24 07:30:00 +0000
As a test displaying the date just created:
NSLog output:
date: 2011-09-24T03:30:00.100-0400
Note that the time and time zone have been converted to my local time zone by NSLog, taking both changes into consideration the date/time are the same as the original.
Web 服务通常用于表示日期/时间的字符串格式是 RFC 3339
它不能是与 NSDate 之间的简单转换,因为它可能包含仅由 NSDate 无法表示的各种信息(例如相对于 UTC 的时间偏移,以及没有指定时间的日期。)
有一些类映射 RFC 3339 与原生 Cocoa 类型之间的字符串,例如 这个。您也许可以通过采用快捷方式的更简单的转换来完成,但对于健壮的代码,请使用专门编写的类来处理表示。
The string format typically used by web services for date/time representation is RFC 3339
It cannot be trivially converted to and from NSDate because it may include a variety of information not representable just by NSDate (such as time offset from UTC, and date with no time specified.)
There are classes which map RFC 3339 strings to and from native Cocoa types, such as this. You may be able to get by with a simpler conversion that takes shortcuts, but for robust code, use a class written specifically to handle the representation.