objective-c - 将 ISO 8601 转换为 NSDate

我有一个来自服务器的时间戳,如下所示:

2013-04-18T08:49:58.157+0000

我已经尝试删除冒号,我已经尝试了所有这些:

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

这是我现在的位置:

+ (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);

https://stackoverflow.com/questions/17558859/

相关文章:

Java - 将双值格式化为美元金额

java - 如何使用 Java 的 DecimalFormat 进行 "smart"货币格式?

python - 以元组为参数的新样式格式

formatting - excel中的数字格式: Showing % value without

javascript - 如何设置 VSCode 以将花括号放在新行上?

asp.net - 如何在 ASP.NET RadioButtonList 中的项目之间添加空格

xml - 如何在 sublime 3 中安装 sublime text indent xml

c - intptr_t 和 uintptr_t 的字符串格式

java - 日期和时间格式取决于区域设置

java - 使用 Java 将电话号码转换为国际格式 (E.164) 的最佳方法是什么?