首页 > 解决方案 > Flutter:按时间戳查询 Firestore 文档

问题描述

我正在尝试通过时间戳字段(例如,在开始日期和结束日期之间)查询 Firestore 文档。时间戳字段返回类似Timestamp(seconds=1599170400, nanoseconds=0).

我的应用程序中有一个 Unix 时间戳(以秒为单位),我想将其与(使用isLessThan:)进行比较,但 Firestore 中的值显然在此 Timestamp 对象内。

我将如何比较这两个时间戳?

另一种方法是查询所有文档并在之后进行比较,但我想过滤查询本身的文档。

标签: fluttergoogle-cloud-firestore

解决方案


要将Timestamp数据库中的 a 与自时代以来的毫秒值进行比较,您可以Timestamp基于该值创建一个对象:

var timestamp = Timestamp.fromMillisecondsSinceEpoch(1599573193925);

然后您可以在查询中针对数据库中的值使用它:

Firestore.instance
.collection('items')
.orderBy('Timestamp', descending: true).startAt([timestamp])

或者(我常用的方法):

Firestore.instance
.collection('items')
.where("Timestamp", isGreaterThanOrEqualTo: timestamp)

推荐阅读