我有一个来自服务器的时间戳,如下所示:
2013-04-18T08:49:58.157+0000
我尝试删除冒号,我尝试了所有这些:
将 ISO 8601 时间戳转换为 NSDate:如何处理 UTC 时间偏移? https://stackoverflow.com/questions/5185230/converting-an-iso-8601-timestamp-into-an-nsdate-how-does-one-deal-with-the-utc
为什么 NSDateFormatter 无法解析 ISO 8601 格式的日期 https://stackoverflow.com/questions/7925038/why-nsdateformatter-can-not-parse-date-from-iso-8601-format
这是我所在的位置:
+ (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
,其他人最后什么也没有。
这对我有用:
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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)