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))
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).
Coordinated Universal Time (UTC) Z is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "T0930Z".
Date.prototype.toISOString() 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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With