将 Firebase Firestore 时间戳转换为日期 (Swift)? [英] Convert Firebase Firestore Timestamp to Date (Swift)?
本文介绍了将 Firebase Firestore 时间戳转换为日期 (Swift)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Firestore 字段中保存了一个日期作为时间戳,我想在 Swift 中将其转换为日期:
I have a date saved in a Firestore field as a timestamp that I want to convert to a Date in Swift:
2018 年 6 月 19 日晚上 7:20:21 UTC-4
我尝试了以下操作,但出现错误:
I tried the following but I get an error:
let date = Date(timeIntervalSince1970: postTimestamp as! TimeInterval)
错误:
无法将 'FIRTimestamp' (0x104fa8b98) 类型的值转换为 'NSNumber'
我想转换为 Date 的原因是我可以使用这个 Date 扩展来模拟你在 Instagram 帖子上看到的时间戳:
The reason why I want to convert to Date is so that I can use this Date extension to mimic timestamps you see on Instagram posts:
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"
}
}
推荐答案
要么:
let date = postTimestamp.dateValue()
或者你可以这样做:
let date = Date(timeIntervalSince1970: postTimestamp.seconds)
请参阅时间戳参考文档.
这篇关于将 Firebase Firestore 时间戳转换为日期 (Swift)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文