比较Cloud Functions中的两个Firestore时间戳

时间:2018-09-09 17:47:18

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

我正在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;
    });

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

3 个答案:

答案 0 :(得分:6)

咨询Firestore的Timestamp object.时间戳的API文档有一个名为isEqual()的方法,该方法将比较两个时间戳。

var result = newTimestamp.isEqual(oldTimestamp);

答案 1 :(得分:2)

您需要添加此行

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

在index.js文件中。

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

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

答案 2 :(得分:0)

//I assume you have yourTimestampInMilliseconds
const currentTimestamp = Date.now();

console.log("(currentTimestamp <= yourTimestampInMilliseconds)= "+ (currentTimestamp <= yourTimestampInMilliseconds));
console.log("(currentTimestamp > yourTimestampInMilliseconds)= "+ (currentTimestamp > yourTimestampInMilliseconds));