NSDateFormatter毫秒错误 [英] NSDateFormatter milliseconds bug

查看:249
本文介绍了NSDateFormatter毫秒错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个NSDateFormatter来解析像这样的日期2014-05-13 23:31:41.374577。所以:

I want to create a NSDateFormatter that should parse dates like this "2014-05-13 23:31:41.374577". So:

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

然而, anotherDateString 2014-05-13 23:31:41.374000 。为什么它会截断毫秒数?

However, the anotherDateString is 2014-05-13 23:31:41.374000. Why does it truncate the milliseconds?

推荐答案

似乎 NSDateFormatter 有效只有毫秒分辨率,对于
以下原因:

It seems that NSDateFormatter works only with millisecond resolution, for the following reasons:


  • 通过在中设置断点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.h 日历使用 UDate ,其分辨率为毫秒级:

    It is stated in calendar.h that Calendar uses UDate which has a millisecond resolution:

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


  • 这篇关于NSDateFormatter毫秒错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆