【发布时间】:2021-01-24 15:48:20
【问题描述】:
我有这样的时间,我必须发送到服务器:
2019-03-06T14:49:55+01:00
我认为我可以这样做:
NSDate(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970))
但我有这样的时间:
2021-01-24 15:42:31 +0000
我以为我必须要用户解码模式,所以用了这样的方式:
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss+z"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let time = NSDate(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970))
if let date = dateFormatterGet.date(from: time.description) {
print(dateFormatterPrint.string(from: date))
} else {
print("There was an error decoding the string")
}
但它的输出是:
There was an error decoding the string
这意味着我这次不能以这种方式解码。我做错了什么?
【问题讨论】:
-
let formatter = ISO8601DateFormatter(); formatter.timeZone = .current; let string = formatter.string(from: Date())