Search code examples
iosswiftnsdateformatteriso8601

Swift ISO8601 format to Date


I have the following string: 20180207T124600Z

How can I turn this into a Date object?

Here is my current code but it returns nil:

let dateString = "20180207T124600Z"
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = .withFullTime
print(dateFormatter.date(from: dateString))

Solution

  • You can specify ISO8601 date formate to the NSDateFormatter to get Date:

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyyMMdd'T'HHmmssZ"
    print(dateFormatter.date(from: dateString)) //2018-02-07 12:46:00 +0000