如何在Swift 4中将Any转换为Date?

时间:2018-02-08 11:30:36

标签: 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)

如果我尝试转换为日期,则抛出错误:

  

'任何?'不能转换为'日期&#39 ;;你的意思是使用' as!'迫使低垂?

当我强制时,返回致命错误

2 个答案:

答案 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)
} }