Compare two Firestore Timestamps in Cloud Functions

Viewed 4534

I'm writing update function in Firestore and I want to compare two Timestamp. I've tried multiple things but not working. Can you point me correct way of comparing two Timestamp in firestore.

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;
    });

I want to check two Timestamp is same or not.

3 Answers

Consult the API docs for Firestore's Timestamp object. Timestamp has a method called isEqual() that will compare two timestamps.

var result = newTimestamp.isEqual(oldTimestamp);

You need to add this line

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

in your index.js file.

After adding this line cloud function will read your timestamp field as Timestamp Datatype. Now you can compare two timestamps using

var result = newTimestamp.isEqual(oldTimestamp);
//I assume you have yourTimestampInMilliseconds
const currentTimestamp = Date.now();

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