Convert ISO 8601 to NSDate

一曲冷凌霜 提交于 2019-11-27 12:40:25

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

There is New API from Apple! NSISO8601DateFormatter

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

I also have the native API, which is way cleaner... This is the implementation I got in my DateTimeManager class:

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

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

Just copy and paste the method, it would do the trick. Enjoy it!

The perfect and best solution that worked for me is:

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

For further more detail, you can refer to apple's official documentation: https://developer.apple.com/documentation/foundation/nsiso8601dateformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!