Roman Simenok
Roman Simenok

Reputation: 570

Right dateFormat for ISO 8601 date

I have stacked with dateFormat of 2017-12-13T10:30:00.000-06:00 for NSDateFormatter. I'd tried different formats but still getting nil from [formatter dateFromString:exampleDate]. The most possible format I had picked up on nsdateformatter was @"yyyy-MM-dd'T'HH:mm:ss.SSSZ" but TimeZone not applying correctly and I got nil from NSDateFormatter.

I also try to use:

NSISO8601DateFormatter *dateFormatter = [[NSISO8601DateFormatter alloc] init];
[dateFormatter dateFromString:@"2017-12-13T10:30:00.000-06:00"];

and also got nil.

Upvotes: 2

Views: 1835

Answers (1)

vadian
vadian

Reputation: 285250

You can use NSISO8601DateFormatter with options .withFractionalSeconds (iOS 11.0+) and .withInternetDateTime

NSISO8601DateFormatter *dateFormatter = [[NSISO8601DateFormatter alloc] init];
dateFormatter.formatOptions = NSISO8601DateFormatWithFractionalSeconds | NSISO8601DateFormatWithInternetDateTime;
NSDate *date = [dateFormatter dateFromString:@"2017-12-13T10:30:00.000-06:00"];
NSLog(@"%@", date);

For a standard NSDateFormatter the date format is correct

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
NSDate *date = [dateFormatter dateFromString:@"2017-12-13T10:30:00.000-06:00"];
NSLog(@"%@", date);

Upvotes: 3

Related Questions