FireStore date query not working as expected

2020-04-20 14:03发布

I have doc which has a date object.

Code to init Firestore:

 FirebaseFirestore fireStore = FirebaseFirestore.getInstance();
        FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
                .setTimestampsInSnapshotsEnabled(true)
                .build();
        fireStore.setFirestoreSettings(settings);
        firestore = fireStore;

Code to query:

FirebaseFirestore db = FireStoreUtils.getInstance();
Query query= db.collection(viewType.collectionName());
        query.whereLessThan("endDate", new Date()); 
        return query.orderBy(viewType.sortProperty()).limit(PAGE_SIZE);

I am always getting all the records and looks like the where clause is not getting applied. On Firebase console I see that the endDate is stored as timestamp.

Doc from Firebase console:

createdDate: null (null)
description: "desc" (string)
endDate: February 3, 2019 at 11:18:58 PM UTC-8 (timestamp)
id: "-7475596197450085332" (string)
title: "title" 

2条回答
2楼-- · 2020-04-20 14:34

I've faced the same problem and my solution comparing and filtering dates is this:

Note that firebase store Date as Timestamp so instead of create a Date to compare, I create a Timestamp instead.

Remember to import Timestamp from Firebase:

import com.google.firebase.Timestamp

Code to query:

val currentDate = Timestamp.now() // Firebase Date as Timestamp

FirebaseFirestore db = FireStoreUtils.getInstance();
Query query= db.collection(viewType.collectionName());
        query.whereLessThan("endDate", currentDate.toDate()); 

return query.orderBy(viewType.sortProperty()).limit(PAGE_SIZE);

I'm using firebase version:

implementation "com.google.firebase:firebase-firestore-ktx:21.3.1"

I hope it helps!!

查看更多
祖国的老花朵
3楼-- · 2020-04-20 14:57

Cloud Firestore queries are immutable, which means that you cannot change the properties of an existing query. If you change the value by calling whereLessThan() method, it becomes a new query. So to solve this, please chain all method calls and store them in a new Query object like this:

Query query = db.collection(viewType.collectionName())
    .whereLessThan("endDate", new Date());
    .orderBy(viewType.sortProperty()).limit(PAGE_SIZE);
    return query;
查看更多
登录 后发表回答