Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 647
user1717140 Avatar asked Dec 08 '22 12:12

user1717140


2 Answers

As of SDK Version 7.10.0, you can directly compare Timestamp objects with the JavaScript arithmetic inequality comparison operators (<, <=, >, and >=).

To check if two Timestamp objects are temporally identical you must use the isEqual property (docs). Comparing with == or === will not check for temporal equality- returning false if comparing different object instances.

SDK release notes here.

Code snippet pulled from corresponding GitHub issue:

a = new Timestamp(1, 1)
b = new Timestamp(2, 2)
console.log(a < b) // true
console.log(b < a) // false
like image 156
willbattel Avatar answered Dec 11 '22 10:12

willbattel


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.

like image 21
Doug Stevenson Avatar answered Dec 11 '22 10:12

Doug Stevenson