首页 > 解决方案 > 从 Android 中的 Firestore 获取过去 24 小时的文档

问题描述

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

我的 Firestore 看起来像:

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

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


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

那当然是。解决此问题的最简单方法是将用户的日期作为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 时间戳,如我在以下帖子中的回答中所述:

如何使用 Android 在 Firestore 中添加时间戳?

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


推荐阅读