0

Using Firebase, the Date is stored as : dd/MM/yyyy in the Firebase DB in String format.
I'm not getting desired results when using orderBy to order my entries by date.

dbInstance.orderByChild("eventDate").startAt(currentDate).addListenerForSingleValueEvent(eventListener);

This is what I'm using to display entries. It works fine. But the problem is with dates not being sorted correctly.

enter image description here

So, if today is 02/05/17 , entry with date in the above image won't display because on comparing these two strings, the one in the image is smaller.

How can this be corrected? Please help!!

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user2940296
  • 143
  • 15

1 Answers1

0

The best practice is to save your data as a TIMESTAMP like this: ServerValue.TIMESTAMP and not as a String.

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map map = new HashMap();
map.put("time", ServerValue.TIMESTAMP);
ref.child("yourNode").updateChildren(map);

And to get the data back, i suggest you use this method:

public static String getTimeDate(long timeStamp){
    try{
        DateFormat dateFormat = getDateTimeInstance();
        Date netDate = (new Date(timeStamp));
        return dateFormat.format(netDate);
    } catch(Exception e) {
        return "date";
    }
}

To solve your problem, you only need to create a query based on the correct DatabaseReference and than orderByValue("timestamp");

Hope it helps.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193