6

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?

Community
  • 1
  • 1
user1717140
  • 303
  • 1
  • 4
  • 13

3 Answers3

14

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
willbattel
  • 911
  • 1
  • 9
  • 30
5

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.

Doug Stevenson
  • 268,359
  • 30
  • 341
  • 380
-1

Have you tried turning your Timestamps into a Date object to be able to then just compare Dates instead of Timestamps?

For example:

const greater = new Date(element.get('expire') as admin.firestore.Timestamp) > new Date();
const lower = new Date(element.get('expire') as admin.firestore.Timestamp) < new Date();
GGR
  • 1
  • 1