【问题标题】:Get every round hour from Firestore从 Firestore 获取每一小时
【发布时间】:2021-09-28 17:00:23
【问题描述】:

我有一个数据存储在 Firestore 中,数据每秒都会添加到 Firestore,所以在 24 小时内我有 1440 个文档(24 * 60),我只想从 Firestore 中提取一个小时以在图表上显示它,我怎样才能从 Firestore 只获得一个小时?

【问题讨论】:

  • 您是否尝试单独获取每个整小时的数据,例如获取时间介于下午 1:00 和下午 2:00 之间的数据?它应该返回你这一小时的那 60 条记录?
  • 不。我试图只获取下午 1:00 和下午 2:00(下午 3:00 等)的日期

标签: flutter google-cloud-firestore


【解决方案1】:

首先,您必须使用时间戳属性存储 Firestore 文档,然后使用 Flutter 的 DateTimeDateFormat API 查询带有时间戳值的文档。

一旦您从 Firestore 获得时间戳,类似于: 时间戳(秒=1560523991,纳秒=286000000)

您可以使用 2 种方式从时间戳值中获取四舍五入的小时数:

你需要把它解析成一个DateTime类型的对象:

DateTime myDateTime = (snapshot.data.documents[index].data['timestamp']).toDate(); // prints 2020-05-09 15:27:04.074

这将以 dart 的 DateTime 格式返回您的 Firestore 时间戳。为了转换您的 DateTime 对象,您可以使用 intl 包中的 DateFormat 类。您可以使用获得的 DateTime 对象来获取您选择的格式,如下所示:

可能的解决方案 1:

DateFormat.Hm().format(myDateTime); //prints 15.27

所以查询应该查找具有以下内容的文档: DateFormat.m().format(myDateTime) to be “00”作为

DateFormat.m() returns minutes and if minutes == 00 then the timestamp is rounded to the nearest hour.

可能的解决方案 2

使用 : 将时间戳转换为时间字符串:

Let TimeString = snapshot.data.documents[index].data['timestamp']).toDate().toString() // prints ‘2019-12-28 18:48:48.364’

Let time = TimeString.split(“ “)[1] // prints 18:48:48.364

To check if the minutes is “00” :
if  time.substring(3,5) == “00”, then it's a rounded hour. //here it is 48

您必须输入这些时间戳转换逻辑,然后按照我提到的四舍五入的小时时间戳进行查询。没有现成的可用功能/方法来获取具有四舍五入时间的 Firestore 文档。

【讨论】:

  • 我的问题只是每隔一小时从firebase获取时间戳数据,而您的答案没有回答..
  • Timestamp firebase 中的对象以 UTC 纪元时间的纳秒分辨率表示为秒和秒的分数。您必须使用 DateFormat 方法/toDate()/toString()/DateTime 方法将其转换为日期时间格式。我不认为我们有一个内置的方法可以直接从 firebase 时间戳获取四舍五入的小时数。因此,我提供了一个替代解决方案,让您了解如何进行转换。尝试实现这一点,如果有问题,请回来。
【解决方案2】:

Firestore 支持"IN" Queries

存储为Timestamp,并尝试关注

const roundhour1 = new Date('2021-10-01T01:00:00.000z');
const roundhour2 = new Date('2021-10-01T02:00:00.000z');

然后编写如下查询:

database.collection("collectionName").where("fieldName", "in", ["roundhour1", "roundhour2"]);

您最多可以有 10 个值 (roundhourX) 来检查“IN”,因此需要触发 3 个查询以获取所有 24 小时数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 2020-12-16
    • 2018-02-28
    相关资源
    最近更新 更多