【问题标题】:Compare two Firestore Timestamps in Cloud Functions比较 Cloud Functions 中的两个 Firestore 时间戳
【发布时间】:2019-02-14 06:13:11
【问题描述】:

我正在 Firestore 中编写更新函数,我想比较两个 Timestamp。我尝试了多种方法,但没有工作。你能指出我在firestore中比较两个Timestamp的正确方法吗?

exports.updateFunction = functions.firestore
    .document('xyz/{xyzId}')
    .onUpdate((change, context) => {
        var updatedXYZ = change.after.data();
        var oldXYZ = change.before.data();

        var newTimestamp = updatedXYZ.timing;
        var oldTimestamp = oldXYZ.timing;

        // I've tried following things but not working

        var result = newTimestamp === oldTimestamp; // not working
        var result = new Date(newTimestamp) - new Date(oldTimestamp); // not working

        return true;
    });

我想检查两个时间戳是否相同。

【问题讨论】:

    标签: node.js google-cloud-firestore google-cloud-functions


    【解决方案1】:
    //I assume you have yourTimestampInMilliseconds
    const currentTimestamp = Date.now();
    
    console.log("(currentTimestamp <= yourTimestampInMilliseconds)= "+ (currentTimestamp <= yourTimestampInMilliseconds));
    console.log("(currentTimestamp > yourTimestampInMilliseconds)= "+ (currentTimestamp > yourTimestampInMilliseconds));
    

    【讨论】:

      【解决方案2】:

      你需要添加这一行

      admin.firestore().settings( { timestampsInSnapshots: true })
      

      在您的 index.js 文件中。

      添加此行云函数后,会将您的时间戳字段读取为 Timestamp 数据类型。现在您可以使用

      比较两个时间戳
      var result = newTimestamp.isEqual(oldTimestamp);
      

      【讨论】:

        【解决方案3】:

        请参阅 API 文档以了解 Firestore 的 Timestamp object. Timestamp 有一个名为 isEqual() 的方法,它将比较两个时间戳。

        var result = newTimestamp.isEqual(oldTimestamp);
        

        【讨论】:

          猜你喜欢
          • 2020-10-22
          • 2021-02-24
          • 2012-02-04
          • 2019-08-26
          • 2015-01-02
          • 2019-02-27
          • 2017-07-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多