Ios NSDateFormatter毫秒错误
我想创建一个NSDateFormatter,它应该像这样解析日期“2014-05-13 23:31:41.374577”。因此:Ios NSDateFormatter毫秒错误,ios,nsdateformatter,Ios,Nsdateformatter,我想创建一个NSDateFormatter,它应该像这样解析日期“2014-05-13 23:31:41.374577”。因此: 但是,另一个日期字符串是2014-05-13 23:31:41.374000。为什么它会截断毫秒数?似乎NSDateFormatter只能以毫秒分辨率工作,对于 原因如下: 通过在CFDateFormatterCreateDateFromString中设置断点,可以 请参见此函数是从dateFromString:调用的: (lldb) bt * thread #1:
但是,另一个日期字符串是
2014-05-13 23:31:41.374000
。为什么它会截断毫秒数?似乎NSDateFormatter
只能以毫秒分辨率工作,对于
原因如下:
- 通过在
中设置断点,可以 请参见此函数是从CFDateFormatterCreateDateFromString
调用的:dateFromString:
(lldb) bt * thread #1: tid = 0x26d03f, 0x018f47d0 CoreFoundation`CFDateFormatterCreateDateFromString, queue = 'com.apple.main-thread', stop reason = breakpoint 3.1 frame #0: 0x018f47d0 CoreFoundation`CFDateFormatterCreateDateFromString frame #1: 0x0116e0ea Foundation`getObjectValue + 248 frame #2: 0x0116dfc7 Foundation`-[NSDateFormatter getObjectValue:forString:errorDescription:] + 206 frame #3: 0x0116879f Foundation`-[NSDateFormatter dateFromString:] + 71 * frame #4: 0x00002d56 foo`main(argc=1, argv=0xbfffee54) + 182 at main.mm:25
来自 这是开源的。可以看出,所有历法计算都是使用CFDateFormatterCreateDateFromString()
- 如所述,
使用具有毫秒分辨率的日历
:UDate
/** * <code>Calendar</code> is an abstract base class for converting between * a <code>UDate</code> object and a set of integer fields such as * <code>YEAR</code>, <code>MONTH</code>, <code>DAY</code>, <code>HOUR</code>, * and so on. (A <code>UDate</code> object represents a specific instant in * time with millisecond precision. See UDate * for information about the <code>UDate</code> class.) * ...
dateFromString
还是stringfromsdate
中的错误?您的[date-timeIntervalSinceReferenceDate]
的小数位数是否与您预期的一样多?似乎[date-timeIntervalSinceReferenceDate]
已四舍五入到小数点后3位……iOS中的NSTimeInterval以毫秒为单位。与java和其他一些语言不同,它是以纳秒为单位测量的。这就是差异的来源。@Fogmeister:NSTimeInterval
是双精度的,精度更高。您还可以在NSDate
和NSTimeInterval
之间进行转换,转换精度超过毫秒。这里的问题似乎是日期格式化程序。
/**
* <code>Calendar</code> is an abstract base class for converting between
* a <code>UDate</code> object and a set of integer fields such as
* <code>YEAR</code>, <code>MONTH</code>, <code>DAY</code>, <code>HOUR</code>,
* and so on. (A <code>UDate</code> object represents a specific instant in
* time with millisecond precision. See UDate
* for information about the <code>UDate</code> class.)
* ...