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?


Solution 1:

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.

Solution 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()

   }