10

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
  • 343
  • 1
  • 5
  • 15

5 Answers5

20

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
  • 1,040
  • 1
  • 10
  • 37
8

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
  • 297,357
  • 32
  • 422
  • 441
0

According to the documentation, we can use the method valueOf() to compare Timestamp. Here the reference of valueOf

tetuaoro
  • 21
  • 4
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/32474690) – Lalaluka Aug 18 '22 at 19:13
0

I can find no documentation for it other than the code itself, but it is worth noting that Timestamp appears to have a _compareTo instance method (at least in my current running version v8.10.1) which returns the sort-friendly -1, 1, and 0 comparison values.

const a = Timestamp.now();

// Some time later
const b = Timestamp.now();

console.log(b._compareTo(a)); // 1
console.log(a._compareTo(b)); // -1
Tanner Stern
  • 128
  • 1
  • 8
-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