簡體   English   中英

如何比較 firebase 時間戳?

[英]How to compare firebase timestamps?

我有這樣的雲 function 代碼代碼:

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:2019 年 4 月 8 日星期一 20:59:59 GMT 現在:2019 年 3 月 8 日星期五 20:19:18 GMT

更大:假 更低:假

那么與時間戳相比如何正確呢?

從 SDK 版本 7.10.0 開始,您可以直接將 Timestamp 對象與 JavaScript 算術不等式比較運算符( <<=>>= )進行比較。

要檢查兩個 Timestamp 對象在時間上是否相同,您必須使用isEqual屬性 ( docs )。 =====比較不會檢查時間相等性 - 如果比較不同的對象實例,則返回false

SDK 發行說明在這里

從相應的 GitHub 問題中提取的代碼片段:

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

您可以通過比較 Timestamp 對象上的secondsnanosecond屬性來做到這一點。 或者,為了更簡單,並且您不需要納秒精度,您可以只比較它們的toMillis()值的結果。

根據文檔,我們可以使用valueOf()方法來比較 Timestamp。 這里是 valueOf 的參考

你有沒有試過把你的時間戳變成一個日期對象,然后只比較日期而不是時間戳?

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM