James Foster
James Foster

Reputation: 71

Is it possible to perform conditions on a Firestore Timestamp?

I'm trying to query my Firestore Database for a list of Sales performed between two dates, that are entered by the user, however, I don't want to query the entire Sale collection and want to only obtain the documents that fall between the two entered dates. I stored the user's entered dates into a Calendar object through the following way:

Calendar startDate = new GregorianCalendar(TimeZone.getDefault());
Calendar endDate = new GregorianCalendar(TimeZone.getDefault());

*I then created an OnDateChangedListener for each DatePicker (one for the start date and one for the end date) and placed the following line depending on which one was clicked*

startDate/endDate.set(year, monthOfYear, dayOfMonth, 0, 0, 0);

The three zeros are for setting the hour, minutes and seconds respectively.

My question is, am I technically able to perform the following query?

db = FirebaseFirestore.getInstance();
db.collection("Sales")
        .whereGreaterThanOrEqualTo("Date", startDate)
        .whereLessThanOrEqualTo("Date", endDate)
        .get()

I have been able to work my way around the other data types for Firestore, the Timestamp is the only one I am struggling to understand and get right. I highly appreciate any feedback.

Edit

I realised upon looking at the question again, that the field names for the database are both the same i.e. "Date" and not "StartDate" and "EndDate". I also placed an image below to showcase what my Sale collection with a single document will look like.

enter image description here

Upvotes: 0

Views: 565

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138969

If you want to query your "Sale" collection by the "Date" property, you have two options. You can either use a Firestore Timestamp object or a Java Date object with a range filter. Passing a Calendar object to the .whereGreaterThanOrEqualTo() and .whereLessThanOrEqualTo() methods, will always yield no results. To solve this problem, you should convert both Calendar objects:

Calendar start = new GregorianCalendar(TimeZone.getDefault());
Calendar end = new GregorianCalendar(TimeZone.getDefault());

Into Date objects like this:

Date startDate = start.getTime();
Date endDate = end.getTime();

Not sure why this method is called getTime() and not getDate(), however it returns the deseired Date object.

Now, the following query:

db = FirebaseFirestore.getInstance();
db.collection("Sales")
        .whereGreaterThanOrEqualTo("Date", startDate)
        .whereLessThanOrEqualTo("Date", endDate)
        .get()

Will return all objects that exist between startDate and endDate.

Upvotes: 2

Related Questions