【问题标题】:Firebase: Code/Formula to convert realtime database timestamp to firestore timestamp?Firebase:将实时数据库时间戳转换为 Firestore 时间戳的代码/公式?
【发布时间】:2020-07-24 20:06:53
【问题描述】:

我在 Firebase 上运行一个网络应用程序,并开始使用实时数据库,现在我正在将我的数据迁移到 Firestore。

我使用管理 SDK 迁移了除时间戳之外的所有其他数据。在我的网络应用程序中,当用户上传新内容时,代码会将时间戳添加到数据库中,以便可以按时间对内容进行排序。

问题是实时数据库和firestore显然在记录时间戳时使用了不同的方法:

firebase.database.ServerValue.TIMESTAMP // This will be in the following format: 1577778747131 
firebase.firestore.Timestamp.now() // This will be in the following format: December 31, 2019 at 4:52:00 PM UTC + 9

另一个问题是 firebase.firestore.Timestamp.now() 显然不是以毫秒或纳秒为单位存储的,而是以系统中的实际日期和时间存储的。所以,我不知道在写入firestore而不是firebase.firestore.Timestamp.now()时要提供什么值(如果有的话)。

在 Javascript 中,将时间戳值从实时数据库转换为 Firebase 时间戳的代码是什么?基本上,填写以下空白的代码是什么:

postinfo.forEach(pi=>{
   const a = pi.time; //Timestamp stored  in realtime database format.
   /*
   Code to transform the timestamp in realtime database to the format to be uploaded to firestore. This I don't know yet.
   */
   const b = new_time;
   // Some code to log the new time instead of the old time. This I can take care of.

我可以花时间使用在线提供的转换器之一,并以新格式手动记录时间,但这需要几个小时,这不是程序员想要做的事情。有关如何执行此操作的任何建议?

【问题讨论】:

    标签: javascript firebase firebase-realtime-database google-cloud-firestore


    【解决方案1】:

    您在实时数据库中指定为 ServerValue.TIMESTAMP 的服务器时间戳在 Firestore 中称为 FieldValue.serverTimestamp()

    Firestore 中的时间戳不像实时数据库那样以毫秒为单位存储为 unix 时间。它们使用两个数字存储,偏移量以秒和纳秒为单位,如Timestamp 的 API 文档中所述。从 Firestore 中读取时间戳类型字段时使用该 Timestamp 对象。

    this article 中详细了解 Firestore 服务器时间戳的工作原理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-09
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 2020-02-23
      • 1970-01-01
      相关资源
      最近更新 更多