我从API获取此日期的字符串格式:“2020-01-02T00:00:00”。

现在,我想将此日期转换为Date格式。这就是我为此所做的...

var utcTime = "\(dic["Due_Date"]!)" //Printing `utcTime` gives "2020-01-02T00:00:00"
self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
self.dateFormatter.locale = Locale(identifier: "en_US")
if let date = dateFormatter.date(from:utcTime) {
  self.scheduledDate = date //HERE I GET THE DATE AS 2020-01-01 18:30:00 UTC
}

字符串格式的接收日期为“2020-01-02T00:00:00”。但是,当我将其转换为Date格式时,我得到的日期是2020-01-01 18:30:00 UTC,这是不正确的。

最佳答案

您必须将时区设置为UTC(世界标准时间)

var utcTime = "2020-01-02T00:00:00" //Printing `utcTime` gives "2020-01-02T00:00:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
if let date = dateFormatter.date(from:utcTime) {
  print(date)  //HERE I GET THE DATE AS 2020-01-01 18:30:00 UTC
}

输出:-
ios - 转换后获取错误的日期格式-LMLPHP

09-10 11:40
查看更多