Search code examples
javascriptfirebasegoogle-cloud-firestorefirebase-admin

How to compare firebase timestamps?


I have cloud function code code like this:

console.log(`ts: ${(element.get('expire') as admin.firestore.Timestamp).toDate().toUTCString()} now: ${admin.firestore.Timestamp.now().toDate().toUTCString()}`)
const greater = (element.get('expire') as admin.firestore.Timestamp) > admin.firestore.Timestamp.now()
const lower = (element.get('expire') as admin.firestore.Timestamp) < admin.firestore.Timestamp.now()
console.log(`greater: ${greater} lower: ${lower}`)

In console:

ts: Mon, 08 Apr 2019 20:59:59 GMT now: Fri, 08 Mar 2019 20:19:18 GMT

greater: false lower: false

So how correctly compare to Timestamps?


Solution

  • You can do this by comparing the seconds and nanoseconds properties on the Timestamp objects. Or, to make it simpler, and you don't need nanosecond precision, you can just compare the results of the results of their toMillis() values.