【问题标题】:Get documents of last 24 hours from Firestore in Android从 Android 中的 Firestore 获取过去 24 小时的文档
【发布时间】:2021-08-24 14:52:17
【问题描述】:

我正在尝试在我的 Android 应用中从 Firestore 获取过去 24 小时的文档。就我而言,文件是邮政持有人。每个帖子文档都有一个包含 Firestore 时间戳的字段。有没有办法在查询中比较时间戳和日期?我将使用设备日期与时间戳进行比较。如果当时的设备日期不正确怎么办?

我的 Firestore 看起来像:

  --- posts (collection)                                                     
   |     |
   |     --- postid (documents)
   |          |
   |          --- country_code: "TR"
   |          |
   |          --- timestamp: Firestore.Timestamp
   |          |
   |          --- post_text: "Some Text" 
   |          |
   |          --- username: "username"

【问题讨论】:

  • 您能否分享有关您的文档外观以及您是否已经在其中存储时间戳字段的更多详细信息?您使用的是 Java 还是 Kotlin?
  • 我编辑了这个问题。我使用 Java 进行开发。

标签: java android firebase google-cloud-firestore


【解决方案1】:

有没有办法在查询中比较时间戳和日期?我将使用设备日期与时间戳进行比较。

确实如此。解决此问题的最简单方法是将用户的日期作为Date 类型的对象获取并执行如下所示的查询:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference postsRef = rootRef.collection("posts");
Query queryByTimestamp = postsRef.whereGreaterThan("timestamp", yourDateObject - 24h);
queryByTimestamp.get().addOnCompleteListener(/* ... /*);

我在你的截图中看到的:

timestamp: "Server.Timestamp"

肯定不行。 timestamp 属性应包含 Date 或 Firestore 时间戳,如我在以下帖子中的回答中所述:

How to add a Timestamp in Firestore with Android?

所以永远不要将Server.Timestamp 添加为字符串。

【讨论】:

  • 感谢您的回复,亚历克斯。但是如果用户设备日期配置不正确怎么办?我将使用此查询来创建提要。
  • 在这种情况下,您还可以考虑编写带有时间戳的文档,读取其值,然后执行查询。这是另一种解决方案。
猜你喜欢
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
  • 2021-03-19
  • 1970-01-01
  • 2019-05-21
  • 2012-07-05
相关资源
最近更新 更多