将 ISO 8601 时间戳转换为 NSDate:如何处理 UTC 时间偏移?
我在将 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(6)
就我而言,我收到了类似的内容:
“2015-05-07T16:16:47.054403Z”
并且我必须使用:
“yyyy'-'MM'-'dd'T'HH':'mm':'ss。 SSZ"
问题是时区偏移内的 :
字符。您可以显式删除该冒号,或删除所有冒号,然后继续。例如:
NSString *s = @"2011-03-03T06:00:00-06:00";
s = [s stringByReplacingOccurrencesOfString:@":" withString:@""];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd'T'HHmmssZZ"];
NSDate *d = [f dateFromString:s];
NSLog(@"%@", d);
此日志:
EmptyFoundation[5088:707] 2011-03-03 12:00:00 +0000
这是我使用的方法:
-(NSDate *)dateFromISO8601String:(NSString *)dateString{
if (!dateString) return nil;
if ([dateString hasSuffix:@"Z"]) {
dateString = [[dateString substringToIndex:(dateString.length-1)] stringByAppendingString:@"-0000"];
}
dateString = [dateString stringByReplacingOccurrencesOfString:@":" withString:@""];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HHmmssZ";
return [dateFormatter dateFromString:dateString];
}
在 Swift 中将 ISO 8601 时间戳转换为 NSDate:
let dateFormatter = NSDateFormatter()
let inputDate = "2015-06-18T19:00:53-07:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ" //iso 8601
let outputDate = dateFormatter.dateFromString(inputDate)
println(outputDate!) //optional implicitly
或者显式可选:
if let outputDate = dateFormatter.dateFromString(inputDate) {
println(outputDate) //no need !
}
Apple 支持 ISO 8601 格式的单独格式
Objective C
NSISO8601DateFormatter *formater = [[NSISO8601DateFormatter alloc]init];
NSString *string = [formater stringFromDate:[NSDate date]];
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
无需删除 : 。要处理“00:00”样式时区,您只需要“ZZZZ”:
Swift
Objective-C
No need to remove the :'s. To handle the "00:00" style timezone, you just need "ZZZZ":
Swift
Objective-C