Swift ISO8601 format to Date

前端 未结 5 1599
庸人自扰
庸人自扰 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条回答
  • 2021-01-18 19:52

    You can use following function to get date...

    func isodateFromString(_ isoDate: String) -> Date? {
    
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyyMMdd'T'HHmmssZ"
        return formatter.date(from: isoDate)
    }
    
    0 讨论(0)
  • 2021-01-18 20:07

    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
    
    0 讨论(0)
  • 2021-01-18 20:15

    ISO8601DateFormatter should be something like

    yyyy-MM-dd'T'HH:mm:ssZ

    as long as your date string is in right format, it won't return nil.

    as for formatOptions, it's Options for generating and parsing ISO 8601 date representations according Apple docs

    Swift 4

    in your example, it should be something like this:

    let dateString = "2016-11-01T21:10:56Z"
    let dateFormatter = ISO8601DateFormatter()
    let date = dateFormatter.date(from: dateString)
    
    let dateFormatter2 = ISO8601DateFormatter()
    dateFormatter2.formatOptions = .withFullTime
    print(dateFormatter2.string(from: date!))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-18 20:18

    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))
    
    0 讨论(0)
提交回复
热议问题