我想知道如何才能以String格式将数据以Timestamp格式发布到Firestore。我正在创建一个示例应用程序,该应用程序将数据存储在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)Firestore中的Timestamp包含日期和时间。如何以String格式将数据以Timestamp格式发布到Firestore
发布于 2018-09-17 21:26:38
如果我理解正确的话,您想在Firestore中以时间戳或日期存储文件?
从字面上看,时间戳就是日期,一种更简单的方法是将其存储为时间戳,因为它只是一个将在Firestore中排序的数字。
let timestamp = Int(NSDate.timeIntervalSinceReferenceDate*1000).description发布于 2018-09-17 21:26:49
为什么你想把它发布为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
}https://stackoverflow.com/questions/52368605
复制相似问题