将 ISO 8601 转换为 NSDate [英] Convert ISO 8601 to NSDate
本文介绍了将 ISO 8601 转换为 NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个来自服务器的时间戳,如下所示:
I have a timestamp coming from server that looks like this:
2013-04-18T08:49:58.157+0000
我已经尝试删除冒号,我已经尝试了所有这些:
I've tried removing the colons, I've tried all of these:
将 ISO 8601 时间戳转换为 NSDate:如何处理 UTC 时间偏移?
为什么 NSDateFormatter 不能从 ISO 8601 解析日期格式
这是我现在的位置:
+ (NSDate *)dateUsingStringFromAPI:(NSString *)dateString {
NSDateFormatter *dateFormatter;
dateFormatter = [[NSDateFormatter alloc] init];
//@"yyyy-MM-dd'T'HH:mm:ss'Z'" - doesn't work
//@"yyyy-MM-dd'T'HH:mm:ssZZZ" - doesn't work
//@"yyyy-MM-dd'T'HH:mm:sss" - doesn't work
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
// NSDateFormatter does not like ISO 8601 so strip the milliseconds and timezone
dateString = [dateString substringWithRange:NSMakeRange(0, [dateString length]-5)];
return [dateFormatter dateFromString:dateString];
}
我最大的问题之一是,我上面的日期格式真的是 ISO 8601 吗?我从人们那里看到的所有示例,每个示例的格式都略有不同.有些有 ...157-0000
,有些最后什么都没有.
One of my biggest questions is, is the date format I have above really ISO 8601? All the examples I have seen from people the formats of each are slightly different. Some have ...157-0000
, others don't have anything at the end.
推荐答案
这对我有用:
NSString *dateString = @"2013-04-18T08:49:58.157+0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
// Always use this locale when parsing fixed format date strings
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocale:posix];
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date = %@", date);
这篇关于将 ISO 8601 转换为 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文