【问题标题】:How to post data to Firestore as Timestamp data type - swift如何将数据作为时间戳数据类型发布到 Firestore - swift
【发布时间】:2019-02-21 10:18:13
【问题描述】:

我想知道如何将数据以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)

Firestore 中的Timestamp 包含日期和时间。 如何将数据以String 发布到FirestoreTimestamp

【问题讨论】:

    标签: swift firebase timestamp google-cloud-firestore


    【解决方案1】:

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

    您似乎将时间戳作为日期进行处理,更简单的方法是将其存储为时间戳,因为它只是将在 Firestore 中订购的数字。

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

    Image Link : This will be the end result

    【讨论】:

    • 我想用当前日期和时间将数据发布到 Firestore。 Firestore 已经提供数据类型为Timestamp,其中包括日期和时间September 17, 2018 at 8:28:29 PM GMT+7。所以,在编程中,我想使用 Timestamp 数据类型将数据发布到 Firestore。
    【解决方案2】:

    为什么要将其发布为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
    }
    

    【讨论】:

    • 我以字符串形式发布,因为当我获取当前时间和日期时,结果将是这样的September 17, 2018 at 8:28:29 PM GMT+7。然后我想将它存储在Firestore 中,稍后,当我查询它时,我可以根据当前日期和时间对其进行排序。例如,最近调用它基于当前日期和时间将数据存储在 tableView 上。我想实现这样的目标。
    猜你喜欢
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 2018-04-30
    • 2012-08-19
    • 2017-07-18
    • 2014-02-22
    • 2020-11-17
    • 2019-02-11
    相关资源
    最近更新 更多