【发布时间】:2011-08-31 07:29:55
【问题描述】:
如何转换该字符串:
2011-08-24T14:06:10Z
使用 NSDateFormatter 到 NSDate。我不知道要设置哪种格式。这个“T”和“Z”是什么意思?
【问题讨论】:
-
我相信 'T' 只是日期和时间之间的分隔符
标签: iphone ios ipad nsstring nsdate
如何转换该字符串:
2011-08-24T14:06:10Z
使用 NSDateFormatter 到 NSDate。我不知道要设置哪种格式。这个“T”和“Z”是什么意思?
【问题讨论】:
标签: iphone ios ipad nsstring nsdate
这是一种 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
【讨论】:
Z 或者您应该将格式化程序的 timeZone 指定为 GMT/UTC。
解析 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)。同样,通过设置dateFormat 和timeZone,此格式化程序还可用于将NSDate 对象转换回2011-08-24T14:06:10Z 等字符串,进行必要的时区转换。最重要的是,这个格式化程序可以双向工作。
使用locale 属性也是最佳做法,因为它可以确保无论设备的特定日历如何(即特别是如果它不是公历)都能正确解释日期。见Technical Q&A 1480。
【讨论】: