Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset?

Tags:

utc

nsdate

iso

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?

like image 259
EJV Avatar asked Mar 03 '11 19:03

EJV


People also ask

Does ISO 8601 use UTC?

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.

Does ISO date include timezone?

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

Is ISO 8601 a string?

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 .


2 Answers

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); 
like image 80
joel.d Avatar answered Sep 22 '22 13:09

joel.d


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"

like image 37
diegomen Avatar answered Sep 24 '22 13:09

diegomen