gpt4 book ai didi

ios - DateFormatter dateFromString 总是在 swift 3 中返回 nil

转载 作者:搜寻专家 更新时间:2023-10-31 08:24:49 27 4
gpt4 key购买 nike

由于某些原因无法将字符串转换为 NSDate。

这是我的日期转换代码:

 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

每次返回nil

最佳答案

强制展开

if  let date : NSDate = (dateFormatter.date(from: dateString)! as NSDate) {
return date
}

如果 dateString 与日期格式不匹配并且 dateFormatter.date(from: dateString) 返回 nil,则程序崩溃。

你可能想要的是

if let date = dateFormatter.date(from: dateString) {
return date
}

或者,如果您确实需要 NSDate 而不是 Date:

if let date = dateFormatter.date(from: dateString) {
return date as NSDate
}

此外,您可能希望将格式化程序的定位设置为“POSIX”

dateFormatter.locale = Locale(identifier: "en_US_POSIX")

为了避免依赖于用户的区域偏好,比较 DateFormatter doesn't return date for "HH:mm:ss" .

关于ios - DateFormatter dateFromString 总是在 swift 3 中返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45282436/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com