javascript - 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();
日期以now
UTC-0 表示,如果我在前一天 22:00 UTC-3 有一个文档,则查询会检索它,但从技术上讲,它不是 Today 文档。
关于如何解决这个问题的任何想法?
解决方案
timestamp
在 firestore 文档中使用而不是日期。
ref.doc(key).set({
created : firebase.firestore.Timestamp.fromDate(new Date("December 10, 1815 19:00:00 EST"))
})
时间戳表示独立于任何时区或日历的时间点,以 UTC 纪元时间的纳秒分辨率表示为秒和秒的分数。
然后,您可以使用该方法toDate()
将时间戳转换为 Date 对象。
推荐阅读
- swift - 我可以使用代码创建一个 NSColor 以便它可以根据暗模式或亮模式进行更改吗?
- angular - 我什么时候应该在 Angular 模块中定义子组件,而不是在父组件中使用选择器?
- javascript - Django/vanilla javascript ajax 发布成功,但页面仍然重新加载
- python-3.x - 格式化具有值列表的有序字典
- bash - 即使使用 Docker 在 Jenkins 上成功构建,我的 Apache 服务器也不会运行
- kotlin - 在 Kotlin 中扩展 2 个具有不同签名的 lambda
- javascript - PHP Laravel如何检查控制器中是否选中了复选框
- excel - 列listobject中非空白单元格的vba变量范围
- excel - 自动搜索所有列
- jquery - 在不删除现有 url 参数的情况下更新或添加 Url 参数