我收到服务器的日期:
// 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)
如果我尝试转换为日期,则抛出错误:
'任何?'不能转换为'日期&#39 ;;你的意思是使用' as!'迫使低垂?
当我强制时,返回致命错误。
答案 0 :(得分:2)
试试这个:
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)
}
}
答案 1 :(得分:0)
尝试以下代码......
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)
} }