It's easy enough to get the ISO 8601 date string (for example, 2004-02-12T15:19:21+00:00
) in PHP via date('c')
, but how does one get it in Objective-C (iPhone)? Is there a similarly short way to do it?
Here's the long way I found to do it:
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
NSDate *now = [NSDate date];
NSString *formattedDateString = [dateFormatter stringFromDate:now];
NSLog(@"ISO-8601 date: %@", formattedDateString);
// Output: ISO-8601 date: 2013-04-27T13:27:50-0700
It seems an awful lot of rigmarole for something so central.
Just use NSISO8601DateFormatter from Foundation framework.
https://developer.apple.com/documentation/foundation/nsiso8601dateformatter?language=objc
Use
NSDateFormatter
:And in Swift:
This is a little bit simpler and puts the date into UTC.
From IS8601, the problems are the representation and time zone
year-month-day time timezone
T
Here are some valid strings
Solutions
NSDateFormatter
So here is the format that I'm using in onmyway133 ISO8601
About the
Z
identifier Date Field Symbol TableAbout
locale
Formatting Data Using the Locale SettingsAbout
en_US_POSIX
Technical Q&A QA1480 NSDateFormatter and Internet DatesInteresting related quetions
An often overlooked issue is that strings in ISO 8601 format might have milliseconds and might not.
In other words, both "2016-12-31T23:59:59.9999999" and "2016-12-01T00:00:00" are legit, but if you are using static-typed date formatter, one of them won't be parsed.
Starting from iOS 10 you should use
ISO8601DateFormatter
that handles all variations of ISO 8601 date strings. See example below:For iOS 9 and below use the following approach with multiple data formatters.
I haven't found an answer that covers both cases and abstracts away this subtle difference. Here is the solution that addresses it:
Usage:
I also recommend checking Apple article about date formatters.
Based on this gist: https://github.com/justinmakaila/NSDate-ISO-8601/blob/master/NSDateISO8601.swift, the following method can be used to convert NSDate to ISO 8601 date string in the format of yyyy-MM-dd'T'HH:mm:ss.SSSZ