如何比较 firebase 时间戳?

How to compare firebase timestamps?

我有这样的云函数代码代码:

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

在控制台中:

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

greater: false lower: false

那么如何正确地与时间戳进行比较?

您可以通过比较 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() 个值来做到这一点。

您是否尝试过将您的时间戳转换为日期对象以便能够只比较日期而不是时间戳?

例如:

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

从 SDK 版本 7.10.0 开始,您可以直接使用 JavaScript 算术不等式比较运算符(<<=>>=).

要检查两个时间戳对象在时间上是否相同,您必须使用 isEqual 属性 (docs)。与 ===== 进行比较不会检查时间相等性 - 如果比较不同的对象实例,则返回 false

SDK release notes here.

提取的代码片段from corresponding GitHub issue:

a = new Timestamp(1, 1)
b = new Timestamp(2, 2)
console.log(a < b) // true
console.log(b < a) // false