Home > Blockchain >  Firestore - filter documents by date range?
Firestore - filter documents by date range?

Time:01-06

A quick sanity check...

I am using Firestore to hold documents where one property is a 'scheduled' date field. I want to retrieve a list of docs filtered by a start-finish date range on the 'scheduled' field.

A few tests on my side, and after reading the Google Firestore docs, suggests that Firestore does not support date range filtering. Is the correct?

CodePudding user response:

You can sort of do this using where query. For this to work you need to store your dates as unixtimestamp

.where("start_time":isGreaterThan,"1506816000").where("startTime":isLessThan, "1507593600")

CodePudding user response:

Firestore does support date filtering. You just need to be careful how you store your dates.

Some people store dates as string, if you store as string with DD-MM-YYYY format, it will make your query invalid because 01-01-2023 < 02-01-2022. But if you store it as a string YYYY-MM-DD, this won't be a problem.

I recommend that you store using the Data object, from firestore itself, you can filter in the following way.

const from = new Date("2023-01-01");
const today = new Date();
const q = query(citiesRef, where("created", "<=", today), where("created", ">=", from));

Or, you can save the dates as unix time, and filter as if they were 2 integers. Firestore is amazing, you can do a lot, it all depends on data modeling.

CodePudding user response:

You can use where query from FirestoreCore package.

example:

Timestamp from = Timestamp(1706316010); Timestamp today = Timestamp.now(); final value = await FirebaseFirestore.instance.collection("collection_name").where("createdAt", isGreaterThan: from).where("createdAt", isLessThan: today).get();";

  • Related