这是下面的数据库。我需要获取作为时间戳的“标题”子项,并将其转换为 Xcode 中的日期格式。
"UserS" : {
"K1eqsVZfKGgIf0sS1UZcPNxY62x1" : {
"Education" : "William Taft Elementary",
"PhotoPosts" : "https://firebasestorage.googleapis.com/v0/b/daylike-2f938.appspot.com/o/images%2FPhotoPosts?alt=media&token=fd92856e-f7d2-4558-82c4-ee49f580icc5e",
"caption" : 1563277511065,
"users" : "jane19@aol.com"
},
这是我在 super View 下加载的内容。
let databaseRef = Database.database().reference()
let uid = Auth.auth().currentUser!.uid
databaseRef.child("UserS").child(uid).child("caption").observeSingleEvent(of: .value, with: { (snapshot) in
guard let message = snapshot.value as? [String:String] else { return }
let caption = message["caption"]
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
guard let date = dateFormatter.date(from: caption!) else {
fatalError("ERROR: Date conversion failed due to mismatched format.")
}
if (snapshot.exists()){
print ("mmmmmmm")
}else{
print("badddddd")
}
})
最后我想以日期格式打印出时间戳,以便我可以检查它是 24 小时前。
最佳答案
“13 位数字时间戳”是自 1970 年 1 月 1 日 UTC 以来的毫秒数
。
Date
自该时间点以来已经具有时间戳的初始值设定项。唯一的区别是它是 seconds
的数量,而不是 milliseconds
。
因此,您唯一应该做的就是将其除以 1000:
// skipping unrelevant boilerplate
// assuming caption is Int
let date = Date(timeIntervalSince1970: TimeInterval(caption)/1000.0) // for `1563277511065` it would be `"Jul 16, 2019 at 11:45 AM"`(UTC)
// skipping unrelevant boilerplate
编辑:
要检查时间戳中的日期是否“早于”24 小时,您有多种选择:
获取
date
和now
之间的差异,并检查它是否在 24 小时内:let secondsInDay = 86400 if (-date.timeIntervalSinceNow < secondsInDay) { … } // negative, because that date would be in the past
在使用日历前获取一天:
let calendar = Calendar.autoupdatingCurrent // or whatever you prefer let dayBefore = calendar.date( byAdding: .day, value: -1, to: Date(), wrappingComponents: true)! if (date > dayBefore) { … }
关于ios - 一旦 13 位时间戳保存在 firebase 中,如何在 Xcode 中获取它并将其转换为日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57058898/