将ISO 8601转换为NSDate [英] Convert ISO 8601 to NSDate
问题描述
我有一个来自服务器的时间戳,如下所示:
2013-04-18T08:49:58.157 + 0000
我尝试删除冒号,我尝试过所有这些:
这是我在哪里: :(NSString *)dateString {
$ p $ +(NSDate *)dateUsingStringFromAPI
NSDateFormatter * dateFormatter;
dateFormatter = [[NSDateFormatter alloc] init];
// @yyyy-MM-dd'T'HH:mm:ss'Z' - 不起作用
// @yyyy-MM-dd'T' HH:mm:ssZZZ - 不起作用
// @yyyy-MM-dd'T'HH:mm:sss - 不起作用
[dateFormatter setDateFormat: @ YYYY-MM-dd'T'HH:MM:ss'Z'];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@GMT]];
// NSDateFormatter不喜欢ISO 8601所以去掉毫秒和时区
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];
//解析固定格式的日期字符串时总是使用这个语言环境
NSLocale * posix = [[NSLocale alloc] initWithLocaleIdentifier:@en_US_POSIX];
[formatter setLocale:posix];
NSDate * date = [formatter dateFromString:dateString];
NSLog(@date =%@,date);
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:
Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset?
Why NSDateFormatter can not parse date from ISO 8601 format
Here is where I am at:
+ (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];
}
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.
This works for me:
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屋!