How to generate a date time stamp, using the format standards for ISO 8601 and RFC 3339?
The goal is a string that looks like this:
"2015-01-01T00:00:00.000Z"
Format:
- year, month, day, as “XXXX-XX-XX”
- the letter “T” as a separator
- hour, minute, seconds, milliseconds, as “XX:XX:XX.XXX”.
- the letter “Z” as a zone designator for zero offset, a.k.a. UTC, GMT, Zulu time.
Best case:
- Swift source code that is simple, short, and straightforward.
- No need to use any additional framework, subproject, cocoapod, C code, etc.
I’ve searched StackOverflow, Google, Apple, etc. and haven’t found a Swift answer to this.
The classes that seem most promising are NSDate
, NSDateFormatter
, NSTimeZone
.
Related Q&A: How do I get an ISO 8601 date on iOS?
Here’s the best I’ve come up with so far:
var now = NSDate()
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
println(formatter.stringFromDate(now))