【问题标题】:Problems with Creating an NSDate object from a ISO 8601 string从 ISO 8601 字符串创建 NSDate 对象的问题
【发布时间】:2012-11-30 01:15:53
【问题描述】:

我在将字符串转换为 NSDate 对象时遇到问题,我不知道为什么。

NSString* tester= @"2012-11-26T10:20:40.187";
NSLog(@"", tester);  //Print the Date String

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSDate *date = [formatter dateFromString:tester];           //Store the date

NSDateFormatter *output = [[NSDateFormatter alloc] init];
[output setDateStyle:NSDateFormatterMediumStyle];
NSLog(@"DATE OBJECT:%@\nDATE STRING: \"%@\"", [output stringFromDate:date]);     //Print the NSDate object and the string

但我似乎得到的只是:

DATE OBJECT:(null)
DATE STRING: "2012-11-26T10:20:40.187"

我认为这与 .187 有关,但我不确定。如果这是重复的,我很抱歉,但我无法弄清楚。

非常感谢您!

【问题讨论】:

  • 187 不是时区,它是毫秒。使用@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS"]

标签: objective-c nsdate iso8601


【解决方案1】:

毫秒的缩写是“S”而不是 Z,它是 TimeZone。 您似乎已经阅读了该示例的正确文档,但是 您错过了 Unicode 技术标准 #35 的链接。 请参阅 NsDateFormatter 文档,搜索“Mac OS X v10.4 中的格式化程序使用版本 tr35-4”。

试试下面的:

[formatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS"];

另见NSDateFormatter Question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 2013-07-07
    相关资源
    最近更新 更多