首页 > 解决方案 > 使用 DateFormatter 解析时正确的时间戳日期格式

问题描述

我有一个时间戳字符串,其形式为:

2018-03-06T06:28:39.887Z

并且需要将其格式化为更易于阅读的格式,我尝试了以下日期格式,但是日期无法解析

 let dateFormatter = DateFormatter()
 dateFormatter.dateFormat = "y-MM-ddTk:mm:ss.SSSZ"
 let date = dateFormatter.date(from: "2018-03-06T06:28:39.887Z")

我的日期格式缺少什么?

标签: swift

解决方案


Swift 3/4 的解决方案:

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26"){
    print(dateFormatterPrint.string(from: date))
}
else {
   print("There was an error decoding the string")
}

推荐阅读