ISO8601DateFormatter doesn't parse ISO date string

前端 未结 4 961
长情又很酷
长情又很酷 2020-12-17 07:40

I\'m trying to parse this

2017-01-23T10:12:31.484Z

using native ISO8601DateFormatter class provided by iOS 1

4条回答
  •  春和景丽
    2020-12-17 08:43

    For people that are not ready to go to iOS 11 yet, you can always create your own formatter to handle milliseconds, e.g.:

    extension DateFormatter {
        static var iSO8601DateWithMillisec: DateFormatter {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
            return dateFormatter
        }
    }
    

    Usage:

    let formater = DateFormatter.iSO8601DateWithMillisec
    let date = formater.date(from: "2017-01-23T10:12:31.484Z")!
    print(date) // output: 2017-01-23 10:12:31 +0000
    

    It is slightly more elegant than writing a regex to strip out the milliseconds from the input string.

提交回复
热议问题