Lucas Gaspar
Lucas Gaspar

Reputation: 331

Storing date in Firebase

I'm doing an app with Ionic and I need to store date in my firebase. But it's getting out of order, i tried methodos like orderByChild(); but nothind is working.

I need my firebase to store like this:

Instead its keeping like this:

There's anyway that I can get it in order?

Here's where I got my date:

function getCurrentDate(){
    var today = new Date();
    console.log(today.getMonth());
    var dd = today.getDate();
    var mm = today.getMonth(); //January is 0!
    var month = new Array();
    month[0] = "Jan";
    month[1] = "Fev";
    month[2] = "Mar";
    month[3] = "Abr";
    month[4] = "Mai";
    month[5] = "Jun";
    month[6] = "Jul";
    month[7] = "Ago";
    month[8] = "Set";
    month[9] = "Out";
    month[10] = "Nov";
    month[11] = "Dez";
    var yyyy = today.getFullYear();

    var currentDate = dd+" "+month[mm]+' '+yyyy;

    return currentDate;
}

Here's where I push into firebase:

function AddServico(date,finalValue,id){
  var deffered = $q.defer();
  var ref = fb.child('/Barbeiro/'+id+'/Dia/'+date+'/');
  ref.once("value")
      .then(function(snapshot) {
          ref.push().set({'finalValue':finalValue});
          deffered.resolve(snapshot);
        });
      ionicToast.show('Adicionado', 'middle', false, 1500);
  return deffered.promise;
}

And here is where I read it from firebase:

function GetDias(id){
    var query = fb.child('Barbeiro/'+id+'/Dia/');
    return $firebaseArray(query).$loaded();
}

Here is how my firebase keep it:

enter image description here

Here's how my app shows it :

enter image description here

Upvotes: 0

Views: 1588

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317412

You're storing dates as string, which is not recommended. Strings are sorted in lexicographical order, which means that the individual characters are compared to each other when performing a sort. This is the same way you'd sort words in a dictionary.

So, for these two strings:

  • 10 Mar 2018
  • 5 Mar 2018

The first string is "less than" the second, because the ascii value of character "1" is less than "5".

If you want to store dates in the database, I'd suggest using a numeric representation instead of a string, usually the number of milliseconds since the unix epoch. These numbers will naturally sort chronologically the way you want.

Upvotes: 1

Related Questions