由於某種原因未能將字符串轉換爲NSDate。DateFormatter dateFromString總是在swift中返回nil
這是我的日期轉換代碼:
let kSQLiteDateFormat : String = "yyyy/MM/dd HH:mm:ss Z"
let dateFormat = [kSQLiteDateFormat,
"dd MM, yyyy",
"MMM-yyyy",
"yyyy-MM-dd",
"yyyy-12",
"yyyy/MM/dd",
"yyyy/mm/dd",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm:ss Z",
"yyyy-MM-dd HH:mm:ss K",
"yyyy-MM-dd HH:mm:ss ZZ",
"yyyy/MM/dd hh:mm a",
"MM/dd/yyyy",
"MM/dd/yyyy HH:mm:ss Z",
"h:mm a",
"hh:mm a",
"yyyy/MM/dd HH:mm:ss Z",
"yyyy/MM/dd h:mm a",
"MM/dd/yyyy h:mm a",
"yyyy-MM-dd h:mm a",
"yyyy-MM-dd'T'hh:mm:ss",
"yyyy/MM/dd h a",
"yyyy-MM-dd'T'HH:mm:ss","dd MMM, yyyy","dd-MM-yyyy HH:mm", "EEE, MMM dd","MM/dd/yyyy hh:mm:ss a"]
if let dateString : String = dateString as String? {
let dateFormatter : DateFormatter = DateFormatter()
for format in dateFormat {
dateFormatter.dateFormat = format
if let date : NSDate = (dateFormatter.date(from: dateString)! as NSDate) {
return date
}
}
}
return nil
每次回零
什麼是你的日期字符串 –
'dateFormat'需要匹配dateString。但是有很多和很多的可能性。你可以嘗試最常見的,但並不意味着它會起作用。什麼是'dateString'。 – Larme
'dateFormatter.date(from:dateString)'返回'Date',而不是'NSDate' –