无法指定类型'日期的值?'键入' String?'斯威夫特3

时间:2018-04-09 09:17:57

标签: swift swift3

//error: Cannot assign value of type 'Date?' to type 'String?'

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.dateStyle = .medium
let date = dateFormatter.date(from: match.dateTimeGMT)
print("date: \(date!)")
cell.dateTimeGMTLabel.text = date  
  

错误:无法指定类型'日期的值?'输入' String?'

1 个答案:

答案 0 :(得分:1)

如果我现在正确理解这个问题。您需要使用新格式从日期重新创建字符串,如下所示:

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

// Change the `...` for your needs
guard let date = dateFormatter.date(from: "2018-05-27T00:00:00.000Z") else { ... }

// Changing the format accordingly or use `DateFormatter.Style`
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
cell.dateTimeGMTLabel.text = dateFormatter.string(from: date)