1

I am trying to sort firebase date by date but it is not working.

I have firebase data structure in this format enter image description here

I use this function to call the node

 var awardsref = CatalogueDB.ref("cageawards/" + mycagecode).orderByChild('Awarddate');

    awardsref.on('value', Awardstable, errData);

this is the output

enter image description here

is there a work around to sort the data based on this date format?

e.iluf
  • 1,389
  • 5
  • 27
  • 69

2 Answers2

4

According to the following page, How query data is ordered, a date is not considered in any sorting way. It first orders null values, then false values, then true, numbers, strings and finally objects.

And all sorting is made following a Lexicographical Order.

So you may need to do the sorting on the client side by your own methods.

There´s another post where you can find an explanation on how to sort by date here

4

As @GerardoHerrera pointed out, Firebase don't support sorting by Date. However, if you parse the dates and convert them to milliseconds based on the UNIX epoch, you should be able to sort them lexicographically according to that.

const date1 = new Date("04-07-2018").getTime();
date1; // 1523084400000

const date2 = new Date("06-02-2018").getTime();
date2; // 1527922800000

Since date1 is less than date2, it will sort as being before date2 in ascending order. Store those converted millisecond time values in your Firebase and you should be able to sort your dataset by them.

e.g.

"7MFD4" {
  ...
  "SPE7L018P1428" {
    "Awarddate": "04-07-2018",
    "AwarddateMS": 1523084400000
    ...
  }
  ...
}

Then do orderByChild('AwarddateMS').

jered
  • 11,220
  • 2
  • 23
  • 34