我将一个日期保存在Firestore字段中作为时间戳,我想将其转换为Swift中的日期:
June 19,2018 at 7:20:21 PM UTC-4
我尝试了以下操作,但出现错误:
let date = Date(timeIntervalSince1970: postTimestamp as! TimeInterval)
错误:
Could not cast value of type 'FIRTimestamp' (0x104fa8b98) to 'NSNumber'
我想转换为Date的原因是为了可以使用此Date扩展名模仿您在Instagram帖子上看到的时间戳:
extension Date {
func timeAgoDisplay() -> String {
let secondsAgo = Int(Date().timeIntervalSince(self))
let minute = 60
let hour = 60 * minute
let day = 24 * hour
let week = 7 * day
if secondsAgo < minute {
return "\(secondsAgo) seconds ago"
} else if secondsAgo < hour {
return "\(secondsAgo / minute) minutes ago"
} else if secondsAgo < day {
return "\(secondsAgo / hour) hours ago"
} else if secondsAgo < week {
return "\(secondsAgo / day) days ago"
}
return "\(secondsAgo / week) weeks ago"
}
}
答案 0 :(得分:14)
可以:
let date = postTimestamp.dateValue()
或者您可以这样做:
let date = Date(timeIntervalSince1970: postTimestamp.seconds)