2014-05-15 14 views
7

Tôi muốn tạo một NSDateFormatter sẽ phân tích các ngày như thế này "2014-05-13 23: 31: 41.374577". Vì vậy:NSDateFormatter mili giây lỗi

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]; 

Tuy nhiên, anotherDateString2014-05-13 23:31:41.374000. Tại sao nó cắt ngắn mili giây?

+6

lẽ nitpicking đây, nhưng có vẻ như để giữ mili giây và cắt ngắn micro giây. –

+0

Lỗi trong 'dateFromString' hoặc' stringFromDate'? Có '[date timeIntervalSinceReferenceDate]' của bạn có nhiều vị trí thập phân như bạn mong đợi không? –

+0

Có vẻ như '[date timeIntervalSinceReferenceDate]' đã được làm tròn thành 3 chữ số thập phân ... –

Trả lời

13

Dường như NSDateFormatter chỉ hoạt động với độ phân giải phần nghìn giây, cho lý do sau:

  • Bằng cách đặt một breakpoint trong CFDateFormatterCreateDateFromString, người ta có thể thấy rằng chức năng này được gọi là từ 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() là từ CFDateFormatter.c là mã nguồn mở. Người ta có thể thấy rằng tất cả các tính toán theo lịch được thực hiện bằng cách sử dụng ICU Calendar Classes.

  • Đó là tuyên bố trong calendar.h rằng Calendar sử dụng UDate trong đó có một độ phân giải millisecond:

    /** 
    * <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

Kết quả thất vọng, nhưng câu trả lời tuyệt vời. Cảm ơn bạn! –