2

I know that it's possible to query by timestamp as seen in previous question, However, what if the date is in the following format:

{
  "lambeosaurus": {
     "date" : "2012-20-03",
     "length" : 12.5,
     "weight": 5000
  },
 "stegosaurus": {
     "date" : "2015-25-13",
     "length" : 9,
     "weight" : 2500
  }
}

How would I go about and query this by date?

Community
  • 1
  • 1
b4oshany
  • 692
  • 1
  • 7
  • 15

2 Answers2

5

You've stored your dates as strings. When Firebase order strings it uses lexicographic ordering. In that order, "2012-20-03" comes before "2012-25-01".

This is the reason why the question you linked to (and the Firebase documentation) usually store dates as timestamps. Those have all the information about the date, in a single number that is guaranteed to be ordered correctly.

Alternatively, you can store the date as a string. But in that case you have to make sure the date is in a format that will lexicographically order correctly too. For your sample that would be: "2012-01-25" and "2012-03-20".

So in this case your only option is to change the data structure to either what was in the original question (and documentation) or to a string format that orders in the order you want.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
2

Convert it to timestamp :

new Date('2012-20-03'.split('-').reverse().join('/')).getTime()

In general :

   function toTimeStamp(dateString){
       return new Date(dateString.split('-').reverse().join('/')).getTime()

   }
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • Wouldn't I have to convert all those dates on firebase before I can query it? – b4oshany Jul 06 '16 at 05:35
  • 2
    Give me github URL of firebase , and , i will rectify the source code to support this syntax : `orderByChild(function(e){return new Date(e.date.split('-').........).getTime()})` – Abdennour TOUMI Jul 06 '16 at 05:40
  • I made a dummy firebase with some dummy data:https://epilog-a3e16.firebaseio.com/flights.json – b4oshany Jul 06 '16 at 05:54