Swift ISO8601 format to Date

前端 未结 5 1634
庸人自扰
庸人自扰 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 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!))
    

提交回复
热议问题