首页 > 解决方案 > Cloud Firestore:在云功能中过滤今天日期的文档

问题描述

我已将包含用户日期和时区的 createdAt 字段存储在 Firestore 文档中。例如(UTC-3 2019 年 12 月 22 日晚上 9:21:42)

然后,我有一个云函数,我想在其中检索所有Today文档。问题是云功能不知道时区,并且在检索不同时区的文档时会变得混乱。

const now: Date = new Date();

const docQuery = await db
   .collection('users')
   .where('createdAt', '>', new Date(now.getFullYear(), now.getMonth(), now.getDate()))
   .where('createdAt', '<', new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59))
   .get();

日期以nowUTC-0 表示,如果我在前一天 22:00 UTC-3 有一个文档,则查询会检索它,但从技术上讲,它不是 Today 文档。

关于如何解决这个问题的任何想法?

标签: javascriptfirebasedategoogle-cloud-firestoregoogle-cloud-functions

解决方案


timestamp在 firestore 文档中使用而不是日期。

ref.doc(key).set({
  created : firebase.firestore.Timestamp.fromDate(new Date("December 10, 1815 19:00:00 EST"))
}) 

时间戳表示独立于任何时区或日历的时间点,以 UTC 纪元时间的纳秒分辨率表示为秒和秒的分数。

然后,您可以使用该方法toDate()将时间戳转换为 Date 对象。


推荐阅读