我想知道如何将数据以String
的形式发布到Firestore
以Timestamp
的形式。我正在创建一个示例应用程序,该应用程序将数据存储在tableView
上,并且数据将基于Timestamp
进行排序。
因此,在编程中,我试图将当前时间和日期设为String
,但由于字段为Firestore
,我不知道如何将数据设置为Timestamp
。当我从Firestore
查询数据时,我想根据Timestamp
对数据进行排序。
let currentDateTime = Date()
// initialize the date formatter and set the style
let formatter = DateFormatter()
formatter.timeStyle = .long
formatter.dateStyle = .long
// get the date time String from the date object
formatter.string(from: currentDateTime)
Timestamp
中的 Firestore
包含日期和时间。
如何将数据以String
的形式发布到Firestore
到Timestamp
的数据中?
答案 0 :(得分:1)
如果我理解正确,您想在Firestore中将带有时间戳或日期的文件存储吗?
您似乎是将字面上的时间戳记作为日期,一种更简单的方法是将其存储为时间戳记,因为它将只是在Firestore中订购的数字。
let timestamp = Int(NSDate.timeIntervalSinceReferenceDate*1000).description
答案 1 :(得分:1)
您为什么要将其发布为String
?这是我用Int
代替的方法
let timestamp = Int(Date().timeIntervalSince1970) // gives you an Int like 1534840591
然后,当您从Firebase
进行解析时,将其传递给func
,就像这样将Int
时间戳转换为日期:
func timestampIntToString(integerTime: Int, timestampLabel: UILabel) {
let timestampDate = Date(timeIntervalSince1970: Double(integerTime))
let now = Date()
let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
let difference = Calendar.current.dateComponents(components, from: timestampDate, to: now)
var timeText = ""
if difference.second! <= 0 {
timeText = "now"
}
if difference.second! > 0 && difference.minute! == 0 {
timeText = "\(difference.second!) sec ago"
}
if difference.minute! > 0 && difference.hour! == 0 {
timeText = "\(difference.minute!) min"
}
if difference.hour! > 0 && difference.day! == 0 {
timeText = "\(difference.hour!)h"
}
if difference.day! > 0 && difference.weekOfMonth! == 0 {
timeText = (difference.day == 1) ? "\(difference.day!)day" : "\(difference.day!) days ago"
}
if difference.weekOfMonth! > 0 {
timeText = (difference.weekOfMonth == 1) ? "\(difference.weekOfMonth!) w" : "\(difference.weekOfMonth!)w"
}
timestampLabel.text = timeText
}