Filtering Firestore data with timestamp from Android App

Issue

Objective: I need to filter the Case Activity entries I have with a particular date so I can display the data from that date on a RecyclerView. And it works fine, when I want to filter with a date range, like so.

    private void filterDate(Date dateFilter1, Date dateFilter2) {
        mFilteredCaseItems.clear();
        Timestamp date1 = new Timestamp(dateFilter1);
        Timestamp date2 = new Timestamp(dateFilter2);
        EventListener<QuerySnapshot> eventListener = createList(CaseActivity.class, mFilteredCaseItems, new FirestoreDateParser.FirestoreDataCallBack() {
            @Override
            public <A extends FireStoreData> void getData(ArrayList<A> data) {
                mAdapter.setItems(data);
                if (mFilteredCaseItems.isEmpty())
                    mFilteredCaseItems.addAll((ArrayList<? extends CaseActivity>) data);
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        db.collection("cases")
                .orderBy("timestamp").startAt(date1).endAt(date2)
                .addSnapshotListener(eventListener);
        Toast.makeText(getContext(), "filter by date", Toast.LENGTH_SHORT).show();
    }

The above works perfectly. But How do I go about filtering with a single date? Not sure comparing timestamps or using whereEqualTo() can help since they take into account the hours and minutes and such. The efforts I made getting the date from both the filter selection date and the Firestore date, and locally comparing them, didn’t work.

Solution

Since you’re storing timestamps in Firestore, the values are exact moments in time with nanosecond granularity. While you can query based on a specific timestamp, you’ll have to specify the specific nanosecond that you want to get back.

If you want to select a specific date on the same data, that translates to a range of timestamps, and thus to either startAt/endBefore filters or >=/< on the timestamp field, starting, typically something like:

.orderBy("timestamp")
  .startAt(timestampAtMidnightOfDay)
  .endBefore(timestampAtMidnightOfNextDay)

If you want to be able to select all documents for a specific date with an equality filter, you’d have to add an additional field to each document with the only the date in a queryable format, typically as a string of format "2022-06-09" (for June 9, 2022).

Answered By – Frank van Puffelen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published