Swift ISO8601 format to Date

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

提交回复
热议问题