首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将数据作为Timestamp数据类型发布到Firestore - swift

如何将数据作为Timestamp数据类型发布到Firestore - swift
EN

Stack Overflow用户
提问于 2018-09-17 21:12:13
回答 2查看 583关注 0票数 0

我想知道如何才能以String格式将数据以Timestamp格式发布到Firestore。我正在创建一个示例应用程序,该应用程序将数据存储在tableView上,数据将基于Timestamp排序。

因此,在编程中,我试图将当前时间和日期设置为String,但我不知道如何将数据设置为Firestore,因为字段为Timestamp。当我从Firestore查询数据时,我希望根据Timestamp对数据进行排序。

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

发布于 2018-09-17 21:26:38

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

从字面上看,时间戳就是日期,一种更简单的方法是将其存储为时间戳,因为它只是一个将在Firestore中排序的数字。

代码语言:javascript
复制
   let timestamp = Int(NSDate.timeIntervalSinceReferenceDate*1000).description

Image Link : This will be the end result

票数 1
EN

Stack Overflow用户

发布于 2018-09-17 21:26:49

为什么你想把它发布为String?下面是我使用Int的方法

let timestamp = Int(Date().timeIntervalSince1970) // gives you an Int like 1534840591

然后,当您从Firebase解析它时,将它传递给类似如下的func,以便将Int时间戳转换为日期:

代码语言:javascript
复制
 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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52368605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档