Ios NSDateFormatter毫秒错误

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:

我想创建一个NSDateFormatter,它应该像这样解析日期“2014-05-13 23:31:41.374577”。因此:


但是,另一个日期字符串是
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.)
 * ...