Search code examples
angularjsfirebasefirebase-realtime-databaseangular-filters

Storing Date input values on Firebase


So this is how my code looks like

cropref.child(mycrop.name).push({
                          cropname:mycrop.name,
                          croplocation:mycrop.location,
                          cropplantdate:mycrop.plantdate.toString(),
                          cropharvestdate:mycrop.harvestdate.toString(),         
                  })

mycrop.harvestdate and mycrop.plantdate are both date inputs from my html

<input type="date" ng-model='mycrop.harvestdate'>

<input type="date" ng-model='mycrop.harvestdate'>

to be able to put the data on my Firebase database , I need to convert it first into string

cropplantdate:mycrop.plantdate.toString(),      

but the data on my Firebase database includes time and timezone

sample data

Sat Dec 12 2020 00:00:00 GMT+0800 (Malay Peninsula Standard Time)

so once I call the data from my database, I can't filter it since it's not a date anymore but a string. How do I solve this problem so that I can filter date (which is converted to string) stored inside my database


Solution

  • Two options

    1) Store the date in a more generic, but human readable format, so right now would be Sunday November 27 at 09:13:38

    20161127091338
    

    2) Store the date as a unix timestamp (in milliseconds) using

    (new Date).getTime() / 1000
    

    There are a lot of variants to #2 so do some research to see which is best for your use case.

    You can save either answer as a string but #1 would be more easily searchable since queries wouldn't require any kind of conversions - to see todays events

    queryStartingAt("20161127") and queryEndingAt("20161127")