在 Objective-C 中解析 ISO8601 日期(iPhone OS SDK)
如何将“2010-04-30T00:45:48.711127”解析为 NSDate? (并保持所有精度)
How do I parse "2010-04-30T00:45:48.711127" into an NSDate? (and maintain all precision)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的工作已经为你完成了。
NSDate
将丢弃任何超过 3 位小数的值(秒)。您可以创建NSDate
的子类来保持该精度,但您还需要实现自己的解析和自定义格式化程序来输入和显示它,因为NSDateFormatter
和 <它所基于的 code>CFDateFormatter 也会截断小数点后 3 位的精度。取决于你在做什么,但这应该不会那么难。这是一个简单的子类(未实现
NSCoding
或NSCopying
),它将保留您赋予它的所有精度。然后,您可以请求
-timeIntervalSince1970
来获取 UNIX 纪元时间。已经有一个 ISO8601 日期/时间解析器类,但由于它使用
NSDateComponents 来生成其日期,目前仅限于整秒精度,但您可以使用它作为起点,也许可以创建更精确的表示。
You have your work cut out for you.
NSDate
will throw out any values past 3 decimal places for seconds. You can create a subclass ofNSDate
to hold on to that precision but you'll also need to implement your own parsing and custom formatters to input and display it sinceNSDateFormatter
andCFDateFormatter
, which it is built on, will also truncate precision after 3 decimal places. Depending on what you're doing though that shouldn't be all that hard.This is a simple subclass (not implementing
NSCoding
orNSCopying
) that will hold on to all the precision you give it.You can then ask for the
-timeIntervalSince1970
to get UNIX epoch time.There is an ISO8601 date/time parser class already out there, but since it's using
NSDateComponents
to generate its date it's limited to full-second precision currently, but you could use it as a starting point perhaps to create more precise representations.我将尝试使用 ISO 8601 解析器和解解析器来处理类似的情况: http://boredzo.org/iso8601parser/< /a>
I'm going to try this ISO 8601 parser and unparser for a similar situation: http://boredzo.org/iso8601parser/
看来 NSDate 只有毫秒精度。
该代码产生以下控制台输出:
因此
"2010-04-30T00:45:48.711127"
可能不会变成"2010-04-30T00:45:48.711000"
你的想法是什么。It seems the NSDate only has millisecond precision.
That code yields the following console output:
So
"2010-04-30T00:45:48.711127"
turning into"2010-04-30T00:45:48.711000"
is probably not what you have in mind.