Mozes Ong
Mozes Ong

Reputation: 1294

Firestore Query by timestemp with flutter

I am adding a document to my collection like this.

void addToDb() {
collectionReference.add({
  'dateTime': FieldValue.serverTimestamp(),
});}

i am trying to query data after a certain date time like this

Firestore.instance
                .collection('items')
                .orderBy('dateTime', descending: true).startAt([{'dateTime' : DateTime.parse('2019-03-13 16:49:42.044')}])
                .snapshots(),

When i set descending to true, i get back all the docs. When i set to false i get back none. Both are not expected results.

I seen a few on stack saying to convert date time to just milliseconds or unix. but i am using the servertimestamp because i cant trust the client to write the time stamp. Any idea how i can query date time ranges with servertimestamp?

Upvotes: 1

Views: 4725

Answers (2)

gsm
gsm

Reputation: 2426

Also you can do as follows,

Firestore.instance
            .collection("driverListedRides")
            .where("uid", isEqualTo: widget.uid.toString())
            .where("status", isEqualTo: "active")
            .where("date",
                isGreaterThanOrEqualTo:
                    DateTime.now().toString().split(" ")[0].toString())
            .orderBy("date", descending: true)
            .orderBy("time", descending: false)

Upvotes: 0

dshukertjr
dshukertjr

Reputation: 18622

I can't really explain why this works, but this works for me.

final startAtTimestamp = Timestamp.fromMillisecondsSinceEpoch(DateTime.parse('2019-03-13 16:49:42.044').millisecondsSinceEpoch);
Firestore.instance
                .collection('items')
                .orderBy('dateTime', descending: true).startAt([startAtTimestamp])
                .snapshots()

Upvotes: 1

Related Questions