fluttergoogle-cloud-firestore

Flutter search date by date range


I have saved data in my Firestore database as DateTime.now().millisecondsSinceEpoch;

I want the user to search by date only using datePicker.

Is it possible to do that or do I have to change my data type in the database? If it's possible, how do I do that?


Solution

  • If you stored the timestamp as milliseconds since the epoch, you can filter on a certain date or date range by using >= and < operators.

    A simple example:

    var now = DateTime.now();
    var start = DateTime(now.year, now.month, now.day);
    var end = start.add(Duration(days: 1));
    
    print(now.millisecondsSinceEpoch);
    print(start.millisecondsSinceEpoch);
    print(end.millisecondsSinceEpoch);
    

    The important variables here:

    So if you want to compare a field in Firestore against these values, it'd be something like:

    collectionRef
      .where("timestampField", isGreaterThanOrEqualTo: start)
      .where("timestampField", isLessThan: end)
      ...