Ios 如何将Swift 4中的任何日期转换为日期?
我从服务器收到一个日期:Ios 如何将Swift 4中的任何日期转换为日期?,ios,swift,casting,ios11,swift4,Ios,Swift,Casting,Ios11,Swift4,我从服务器收到一个日期: // It comes from server as Any let. let userInfo: [AnyHashable : Any] let userInfoDic = userInfo as NSDictionary userInfoDic.value(forKey: "gcm.notification.date") as Any // prints Optional(2018-04-26) 如果我尝试转换为日期,则抛出错误: “任何?”不能转换为“日期”
// It comes from server as Any let.
let userInfo: [AnyHashable : Any]
let userInfoDic = userInfo as NSDictionary
userInfoDic.value(forKey: "gcm.notification.date") as Any
// prints Optional(2018-04-26)
如果我尝试转换为日期,则抛出错误:
“任何?”不能转换为“日期”;你想用“as”吗迫使沮丧
强制时,返回一个致命错误。请尝试以下操作:
if let dateString = userInfoDic.value(forKey: "gcm.notification.date") as? String {
let dateFormatter = DateFormatter()
dateFormatter.format = "yyyy-MM-dd"
if let date = dateFormatter.date(from: dateString) {
print(date)
}
}
请尝试下面的代码
if let date = userInfoDic.value(forKey: "gcm.notification.date") as? Any {
let dateString = String(describing: date)
let dateFormatter = DateFormatter()
dateFormatter.format = "yyyy-MM-dd"
if let date = dateFormatter.date(from: dateString) {
print(date)
} }
你试过DateFormatter()吗?“如果让date=userInfoDic.value(forKey:“gcm.notification.date”)作为?Any”这总是正确的。你可以使用它作为你的请求,只需使用
userInfo[“gcm.notification.date”]
。不要在Swift中使用NSDictionary
。此外,还必须将格式化程序区域设置设置为POSIX。