Swift ISO8601 format to Date

前端 未结 5 1628
庸人自扰
庸人自扰 2021-01-18 19:20

I have the following string: 20180207T124600Z

How can I turn this into a Date object?

Here is my current code but it returns nil:<

5条回答
  •  旧时难觅i
    2021-01-18 20:16

    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.

提交回复
热议问题