【问题标题】:How do you interpret dates with NSDateFormatter?你如何用 NSDateFormatter 解释日期?
【发布时间】:2009-10-13 09:44:14
【问题描述】:

在 Apple Docs 中,他们说 NSDateFormatter 使用 Unicode 作为规范。我已经阅读了规范,但是我在解释这个日期时遇到了麻烦:

NSDateFormatter *frm = [[NSDateFormatter alloc] init];
[frm setDateFormat:@"EEE MMM dd HH:mm:ss ZZZ yyyy"];
NSLog(@"Tue Oct 13 09:24:15 +0000 2009 becomes %@", [frm dateFromString:@"Tue Oct 13 09:24:15 +0000 2009"]);

这段代码打印出来:

2009-10-13 11:37:40.334 test2[1704:20b] Tue Oct 13 09:24:15 +0000 2009 becomes (null)

【问题讨论】:

    标签: iphone nsdateformatter


    【解决方案1】:

    对不起,伙计们,已经想通了。 NSDateFormatter 默认使用当前系统语言环境。在上面的代码示例中,仅当您将系统区域设置为美国以外的其他设置时它才会失败。要修复它,就在将区域设置设置为日期字符串使用的区域之前,如下所示:

    [frm setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
    

    【讨论】:

    • 我刚刚遇到了同样的问题。这与当前日期和时间设置(12/24 小时)有关。我试图使用yyyy-MM-dd HH:mm:ss 解析日期2004-11-29 16:01:26。仅当我强制使用语言环境时才有效:[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"] autorelease]]; 令人困惑,但它有效!
    猜你喜欢
    • 2016-07-23
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    相关资源
    最近更新 更多