如何以格式化样式swift获取系统时间?

如何以格式化样式swift获取系统时间?,swift,nsdate,decoding,Swift,Nsdate,Decoding,我有这样的时间,我必须发送到服务器: 2019-03-06T14:49:55+01:00 我想我可以这样做: NSDate(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970)) let dateFormatterGet = DateFormatter() dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss+z" let dateForma

我有这样的时间,我必须发送到服务器:

2019-03-06T14:49:55+01:00
我想我可以这样做:

NSDate(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970))
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")
}
但我有这样的时间:

2021-01-24 15:42:31 +0000
我认为我必须使用用户解码模式,所以使用这种方式:

NSDate(timeIntervalSince1970: TimeInterval(NSDate().timeIntervalSince1970))
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

这意味着我这次不能以这种方式解码。我做错了什么?

您正在从日期的时间间隔创建一个日期字符串,其中三个转换是浪费的

转换失败,因为
time.description
与格式
yyyy-MM-dd HH:MM:ss+z不匹配

要获取带时区的ISO8601字符串,日期格式为
yyyy-MM-dd'T'HH:MM:ssZ
,并且必须指定固定的区域设置

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let isoString = formatter.string(from: Date())
正如Rob在评论中所建议的,有一种较短的方法

let formatter = ISO8601DateFormatter()
formatter.timeZone = .current
let isoString = formatter.string(from: Date())

let formatter=ISO8601DateFormatter();formatter.timeZone=.current;让string=formatter.string(from:Date())