2014-05-15 100 views
7

我想創建一個NSDateFormatter,它應該解析像這樣的「2014-05-13 23:31:41.374577」日期。所以:NSDateFormatter毫秒bug

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。爲什麼它截斷毫秒?

+6

也許挑剔這裏,但它似乎保持毫秒,截斷微秒。 –

+0

是'dateFromString'或'stringFromDate'中的錯誤嗎?你的'[date timeIntervalSinceReferenceDate]'是否有你期望的小數位數? –

+0

似乎'[date timeIntervalSinceReferenceDate]'已經四捨五入到小數點後3位...... –

回答

13

似乎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.) 
    * ... 
    
+2

令人失望的結果,但真棒的答案。謝謝! –