【问题标题】:NSString to NSDate conversion. Problem with "2011-08-24T14:06:10Z"NSString 到 NSDate 的转换。 “2011-08-24T14:06:10Z”的问题
【发布时间】:2011-08-31 07:29:55
【问题描述】:

如何转换该字符串:

2011-08-24T14:06:10Z

使用 NSDateFormatter 到 NSDate。我不知道要设置哪种格式。这个“T”和“Z”是什么意思?

【问题讨论】:

  • 我相信 'T' 只是日期和时间之间的分隔符

标签: iphone ios ipad nsstring nsdate


【解决方案1】:

这是一种 RFC3339 日期格式。

您可以使用以下方法解析它:

NSDateFormatter* rfc3339DateFormatter = [[NSDateFormatter alloc] init];

[rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];

NSDate* date = [rfc3339DateFormatter dateFromString:yourString]; 

[aDateFormatter release];

更多信息请访问Apple Formatting Dates Documentation 您还可以找到更多关于 RFC3339 日期格式的信息(关于 T 和 Z)in this section of the RFC3339 standard

【讨论】:

  • 其实格式是:@"yyyy-MM-dd'T'HH:mm:ss'Z'"。感谢您的帮助
  • 这是不正确的。您不能引用 Z 或者您应该将格式化程序的 timeZone 指定为 GMT/UTC。
【解决方案2】:

解析 RFC 3339/ISO 8601 日期的方法如下:

NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZZ";
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

或者,在 macOS 10.12 和 iOS 10 中:

NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];

然后:

NSDate* date = [formatter dateFromString:dateString]; 

注意,ZZZZZ 告诉格式化程序在将字符串转换为 NSDate 对象时使用字符串中存在的时区(其中 GMT+0 表示为 Z)。同样,通过设置dateFormattimeZone,此格式化程序还可用于将NSDate 对象转换回2011-08-24T14:06:10Z 等字符串,进行必要的时区转换。最重要的是,这个格式化程序可以双向工作。

使用locale 属性也是最佳做法,因为它可以确保无论设备的特定日历如何(即特别是如果它不是公历)都能正确解释日期。见Technical Q&A 1480

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多