How to compare firebase timestamps?

强颜欢笑 提交于 2020-04-16 03:20:06

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/55070600/how-to-compare-firebase-timestamps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!