Swift ISO8601 format to Date
If you have a date such as:
let isoDate = "2018-12-26T13:48:05.000Z"
and you want to parse it into a Date, use:
let isoDateFormatter = ISO8601DateFormatter()
isoDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
isoDateFormatter.formatOptions = [
.withFullDate,
.withFullTime,
.withDashSeparatorInDate,
.withFractionalSeconds]
if let realDate = isoDateFormatter.date(from: isoDate) {
print("Got it: \(realDate)")
}
The important thing is to provide all the options for each part of the data you have. In my case, the seconds are expressed as a fraction.
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
You need to specify the format options for the ISO8601DateFormatter
to match your requirements (year, month, day and time), here is an example below:
//: Playground - noun: a place where people can play
import UIKit
let dateString = "20180207T124600Z"
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = [
.withYear,
.withMonth,
.withDay,
.withTime
]
print(dateFormatter.string(from: Date()))
print(dateFormatter.date(from: dateString))