将ISO 8601转换为NSDate

问题描述 投票:29回答:4

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

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,有些人最后没有任何东西。

objective-c formatting nsdate nsdateformatter iso
4个回答
61
投票

这对我有用:

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

16
投票

Apple有新的API! NSISO8601DateFormatter

NSString *dateSTR = @"2005-06-27T21:00:00Z";
NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
NSDate *date = [formatter dateFromString:dateSTR];
NSLog(@"%@", date);

2
投票

我也有原生API,这是更清洁......这是我在DateTimeManager类中得到的实现:

+ (NSDate *)getDateFromISO8601:(NSString *)strDate{

    NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
    NSDate *date = [formatter dateFromString: strDate];
    return date;
}

只需复制并粘贴方法,就可以了。好好享受!


0
投票

对我有用的完美和最佳解决方案是:

let isoFormatter = ISO8601DateFormatter();
isoFormatter.formatOptions = [ISO8601DateFormatter.Options.withColonSeparatorInTime,
                                      ISO8601DateFormatter.Options.withFractionalSeconds,
                                      ISO8601DateFormatter.Options.withFullDate,
                                      ISO8601DateFormatter.Options.withFullTime,
                                      ISO8601DateFormatter.Options.withTimeZone]
let date = isoFormatter.date(from: dateStr);

有关更多详细信息,请参阅apple的官方文档:https://developer.apple.com/documentation/foundation/nsiso8601dateformatter

© www.soinside.com 2019 - 2024. All rights reserved.