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.
The perfect and best solution that worked for me is:
For further more detail, you can refer to apple's official documentation: https://developer.apple.com/documentation/foundation/nsiso8601dateformatter
This works for me:
There is New API from Apple!
NSISO8601DateFormatter
I also have the native API, which is way cleaner... This is the implementation I got in my DateTimeManager class:
Just copy and paste the method, it would do the trick. Enjoy it!