首页 > 解决方案 > 如何比较 Firestore 时间戳对象

问题描述

使用带有 Cloud Scheduler 的 CloudFunctions 从 Firestore 获取时间戳数据。然后我想比较时间戳数据。具体来说,Cloud Functions 使用 Cloud Scheduler 在每天 12:00 执行。我想检查firestore的时间戳在执行时是否超过10天。如果超过,则执行特定流程。

如果我可以在从 Firestore 获得的时间戳上加上 10 天,那将是可比的,但它不起作用。具体来说,我尝试使用 toDate() 将时间戳转换为日期并尝试添加 10 天。

标签: firebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


Timestamp.valueOf()方法是使用 >、<=、>= 和 > 运算符执行时间戳比较的最简单方法。但是,如果您正在处理向其中一个时间戳添加时间,那么比较秒数可能是最简单的,如下所示:

const TEN_DAYS_IN_SECONDS = 60 * 60 * 24 * 10;
const timestamp_a = firestore.Timestamp.now();
const timestamp_b = firestore.Timestamp.now();

console.log(timestamp_a.seconds + TEN_DAYS_IN_SECONDS > timestamp_b.seconds);
// output: true

推荐阅读