I have a collection of documents with a timestamp field named ‘date’. I want to query a single document with the specific ‘date’: 2024/02/29 00:00:00 GMT05.30.
So in Flutter, I’m trying to get that doc by using the following query
StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('mycolloection').where('date', isEqualTo: DateTime(2024,2,29,0,0,0,0,0),).snapshots(),),
but the above code does not retrieve any documents. So I played with isGreaterThan and isLesserThan for several hours and found out there is a hidden milliseconds value in the Firestore timestamp. So I have to give a milliseconds value as well. But this value is changing with different dates and it looks like a completely random number. Can anyone explain what is happening here…
2
Answers
As I understand from your question, you store the
date
in Firestore in the following format:Which is not quite correct. Such a field can exist inside a document in Firestore only as a string. I’m saying that because
GMT (Greenwich Mean Time)
is a timezone and the timestamps in Firestore don’t encode timezones. The timezone of the Firestore timestamp is UTC.If you need to work with date and time, then you should use a Firestore Timestamp, which is a supported data type in Firestore. So once you set the field with the correct data type, you can then perform a query.
Please also note that when you call
where()
you have to pass a timestamp object and not aDateTime
. If you do so, you’ll never get the desired results.When you want to use the
isEqualTo
operation to match a timestamp, you’ll have to match the exact timestamp that is stored in the database. To make that feasible, you’ll need to ensure that you store the timestamp with 0 milliseconds and 0 microseconds too.For example:
The
today
variable will not have just the date part, with all time parts set to0
.