【发布时间】:2019-12-16 11:28:13
【问题描述】:
我这里有一些奇怪的情况
我正在尝试将我的 dateString 转换为 Date,只要我的日期有小数毫秒(值超过 000),它就会失败
2019-12-16T10:23:47.000Z // works fine
2019-12-16T10:23:47.673Z // fails
这是我的字符串扩展
extension String {
func getFormattedDate() -> String {
let dateFormatterGet = DateFormatter()
// "2019-12-16T10:23:47.000Z"
dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "dd-MM-yy"
let date: Date? = dateFormatterGet.date(from: self)
// here date value returns nil when i have fractional milliseconds
print("Date",dateFormatterPrint.string(from: date!)) // prints 16-12-19
//it fails in below line saying "Fatal error: Unexpectedly found nil while unwrapping
// an Optional value" as date returns nil
return dateFormatterPrint.string(from: date!);
}
}
提前致谢
【问题讨论】:
-
使用
SSS表示小数秒,而不是sss。
标签: swift date dateformatter