如何将数据作为时间戳数据类型发布到Firestore-swift

时间:2018-09-17 13:12:13

标签: swift firebase timestamp google-cloud-firestore

我想知道如何将数据以String的形式发布到FirestoreTimestamp的形式。我正在创建一个示例应用程序,该应用程序将数据存储在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的形式发布到FirestoreTimestamp的数据中?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您想在Firestore中将带有时间戳或日期的文件存储吗?

您似乎是将字面上的时间戳记作为日期,一种更简单的方法是将其存储为时间戳记,因为它将只是在Firestore中订购的数字。

   let timestamp = Int(NSDate.timeIntervalSinceReferenceDate*1000).description

Image Link : This will be the end result

答案 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
}