Home > front end >  How to query for an entire day with timestamp values in Firestore
How to query for an entire day with timestamp values in Firestore

Time:08-07

I have a firestore collection 'orders' whose documents has a timeStamp value. I want to filter documents of that collection based on timeStamp. For example, filter orders placed on July 1 ,2022. I pass date value got from Datepicker as DateTime. The query i formed is

_db.collection('orders')
        .where('driverId', isEqualTo: sp.getString('uid'))
        .where('timeStamp', isGreaterThanOrEqualTo: Timestamp.fromDate(pickedDate!))
        .get().then((querySnapshot){
      querySnapshot.docs.forEach((element) {
        orders.add(element.data());
      });
      print(orders.length);
    });

The problem is i'm getting orders from July 1 till today since i have given isGreaterThanOrEqualTo. But if i give isEqualTo,it returns nothing. Means it takes 01-07-2022 00:00:00 i guess. So what is the correct query to get orders on a selected date?

CodePudding user response:

Timestamp objects in Firestore are very specific points in time, with a microsecond precision. So if you want to match all timestamps for an entire day, that is a range of timestamp values.

The typical approach is to create a timestamp of one day later, and then add that to the second clause needed for the range:

_db.collection('orders')
    .where('driverId', isEqualTo: sp.getString('uid'))
    .where('timeStamp', isGreaterThanOrEqualTo: Timestamp.fromDate(pickedDate!))
    .where('timeStamp', isSmallerThan: timestampOfStartOfNextDay)
  • Related