我试图返回一个ISO8601日期并将其附加到数组上,但是我一直遇到问题。由于某些原因,我一直遇到致命错误,因为它在展开可选值时发现nil。但是我知道绝对有价值。我格式化不正确吗?
time-released format->“ 2006-11-30T00:00:00.000Z”
if movieInfo.time_released != nil {
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from: movieInfo.time_released!)
let dateString = dateFormatter.string(from: date!)
array.append(dateString)
}
答案 0 :(得分:3)
默认的ISO8601格式化程序不解析小数秒,因此当您尝试解析包含秒的日期字符串时,它返回nil。如果要小数秒,则需要请求它们:
import Foundation
let time_released = "2006-11-30T00:00:00.000Z"
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions.insert(.withFractionalSeconds)
if let date = dateFormatter.date(from: time_released) {
let dateString = dateFormatter.string(from: date)
print(dateString)
}