【问题标题】:NSDateFormatter milliseconds bugNSDateFormatter 毫秒错误
【发布时间】:2014-05-15 17:13:26
【问题描述】:

我想创建一个 NSDateFormatter 来解析日期,如“2014-05-13 23:31:41.374577”。所以:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSSSSS";
NSString *dateString = @"2014-05-13 23:31:41.374577";
NSDate *date = [formatter dateFromString:dateString];
NSString *anotherDateString = [formatter stringFromDate:date];

但是,anotherDateString2014-05-13 23:31:41.374000。为什么会截断毫秒?

【问题讨论】:

  • 也许在这里吹毛求疵,但它似乎保留毫秒并截断微秒。
  • 错误是在dateFromString 还是stringFromDate?您的[date timeIntervalSinceReferenceDate] 的小数位数是否与您预期的一样多?
  • 看来[date timeIntervalSinceReferenceDate]已经四舍五入到小数点后三位了……
  • iOS 中的 NSTimeInterval 以毫秒为单位。与 java 和其他一些以纳秒为单位的语言不同。这就是差异的来源。
  • @Fogmeister:NSTimeInterval 是双精度型,精度更高。您还可以在NSDateNSTimeInterval 之间进行转换,精度超过毫秒。这里的问题似乎是日期格式化程序。

标签: ios nsdateformatter


【解决方案1】:

似乎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() 来自 CFDateFormatter.c 这是开源的。可以看出,所有历法计算都是使用 ICU Calendar Classes.

  • calendar.h 中声明Calendar 使用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.)
     * ...
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多