Home > OS >  How do i order by Date Firebase
How do i order by Date Firebase

Time:10-08

I have some entries in a database and and they all contain a date string.

I have some TS like this

ref.LimitToFirst(10).orderByChild('date')

The problem i an having is that TS treats this as a regular string and just orders by the first number in the date. ex - 10/1/2021 would be ordered before 2/1/2021. How could i fix that ?

CodePudding user response:

You can't fix this in code while depending on the database to perform the query. In Realtime Database, strings will always sort lexicographically - by their natural string order. You can't make it interpret the strings as something other than a normal string.

You will have to instead store an integer value that you can sort chronologically. In JavaScript, you can simply create a Date object and use its getTime() method field to get the Date's representation in millis since the unix epoch.

If you can't store a proper timestamp, then your only option is to read all the data and sort it yourself in your app, which will not scale well.

  • Related