I'm having trouble converting an ISO 8601 timestamp into an NSDate
. I tried to use NSDateFormatter
, but I can't get it to work with the UTC time offset that appears on the end of the timestamps. To explain, I would like to convert a timestamp such as the following into an NSDate
: 2011-03-03T06:00:00-06:00
. My question is: How do I deal with the "-06:00" part? I tried using yyyy-MM-dd'T'HH:mm:ssZ
as my date format string but it doesn't work. Any suggestions?
ISO 8601 applies to these representations and formats: dates, in the Gregorian calendar (including the proleptic Gregorian calendar); times, based on the 24-hour timekeeping system, with optional UTC offset; time intervals; and combinations thereof.
ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).
The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .
No need to remove the :'s. To handle the "00:00" style timezone, you just need "ZZZZ":
Swift
let dateString = "2014-07-06T07:59:00Z" let dateFormatter = NSDateFormatter() dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ" dateFormatter.dateFromString(dateString)
Objective-C
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; dateFormat.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; NSString *input = @"2013-05-08T19:03:53+00:00"; [dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"]; //iso 8601 format NSDate *output = [dateFormat dateFromString:input]; NSLog(@"Date output: %@", output);
In my case I received something like that:
"2015-05-07T16:16:47.054403Z"
And I had to use:
"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZ"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With