Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 338
Balázs Vincze Avatar asked Feb 19 '18 13:02

Balázs Vincze


People also ask

Is ISO 8601 valid date?

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).

What is Z in ISO 8601 date format?

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".

Is ISO 8601 always UTC?

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 .


1 Answers

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.

like image 126
P. Ent Avatar answered Nov 01 '22 05:11

P. Ent