1

I am trying to get documents of the last 24 hours from Firestore in my Android app. In my case, documents are post holders. Every post document has a field that holds Firestore Timestamp. Is there a way to compare timestamp to date in a query? I will use device date to compare to timestamp. What if the device date is not correct at the time?

My Firestore looks like:

  --- posts (collection)                                                     
   |     |
   |     --- postid (documents)
   |          |
   |          --- country_code: "TR"
   |          |
   |          --- timestamp: Firestore.Timestamp
   |          |
   |          --- post_text: "Some Text" 
   |          |
   |          --- username: "username"
Nasir
  • 57
  • 5
  • 2
    Can you share more details about how you document looks like and if you are already storing a timestamp field in it ? Are you using Java or Kotlin? – Dharmaraj Aug 24 '21 at 14:55
  • I edited the question. I use Java for development. – Nasir Aug 24 '21 at 15:01

1 Answers1

1

Is there a way to compare timestamp to date in a query? I will use device date to compare to timestamp.

It certainly is. The simplest way to solve this would be to get the User's date as an object of type Date and perform a query that looks like this:

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

What I see in your screenshot:

timestamp: "Server.Timestamp"

It Will definitely not work. The timestamp property should contain a Date or a Firestore timestamp as explained in my answer from the following post:

How to add a Timestamp in Firestore with Android?

So never add the Server.Timestamp as a String.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thanks for reply, Alex . But what if user device date is incorrectly configured? I will use this query to create feed. – Nasir Aug 24 '21 at 15:21
  • In that case, you might also consider writing a document with a timestamp, read its value, and then perform the query. That's an alternative solution. – Alex Mamo Aug 24 '21 at 15:39