将ISO 8601时间戳转换为NSDate:如何处理UTC时间偏移? [英] Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset?
问题描述
我无法将 ISO 8601 时间戳转换为NSDate
.我尝试使用NSDateFormatter
,但无法使其与时间戳末尾出现的 UTC 时间偏移配合使用.为了说明,我想将如下所示的时间戳转换为NSDate
:2011-03-03T06:00:00-06:00
.我的问题是:如何处理"-06:00"部分?我尝试使用yyyy-MM-dd'T'HH:mm:ssZ
作为日期格式字符串,但是它不起作用.有什么建议吗?
I'm having trouble converting an ISO 8601 timestamp into an NSDate
. I tried to use NSDateFormatter
, but I can't get it to work with the UTC time offset that appears on the end of the timestamps. To explain, I would like to convert a timestamp such as the following into an NSDate
: 2011-03-03T06:00:00-06:00
. My question is: How do I deal with the "-06:00" part? I tried using yyyy-MM-dd'T'HH:mm:ssZ
as my date format string but it doesn't work. Any suggestions?
推荐答案
无需删除:.要处理"00:00"样式的时区,您只需要"ZZZZ":
No need to remove the :'s. To handle the "00:00" style timezone, you just need "ZZZZ":
快速
let dateString = "2014-07-06T07:59:00Z"
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
dateFormatter.dateFromString(dateString)
Objective-C
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSString *input = @"2013-05-08T19:03:53+00:00";
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"]; //iso 8601 format
NSDate *output = [dateFormat dateFromString:input];
NSLog(@"Date output: %@", output);
这篇关于将ISO 8601时间戳转换为NSDate:如何处理UTC时间偏移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!