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

时间:2022-04-01 15:59:24

I am receiving an date from server:

我从服务器收到日期:

// 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)

If I try convert to date, throws the error:

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

‘Any?’ is not convertible to 'Date'; did you mean to use 'as!' to force downcast?

“任何?”不能兑换为“日期”;你的意思是用'as!'迫使低垂?

When I force, returns an fatal error.

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

2 个解决方案

#1


2  

Try this:

尝试这个:

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

#2


0  

Try below code....

试试以下代码......

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

#1


2  

Try this:

尝试这个:

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

#2


0  

Try below code....

试试以下代码......

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