Hasan Hasanzade
Hasan Hasanzade

Reputation: 13

Sorting events according to date in Firebase

I have news data in Firebase in following format:

enter image description here

I want to sort it according to date (newsDate) in descending order (latest on the top). I have added this to my code while I am retrieving data from Firebase:

databaseReference.orderByChild("newsDate").addChildEventListener(new ChildEventListener() { // on child added methods }

But this only does string sorting, so that order becomes like this: 04/08/2018 12:00, 13/08/2018 10:30, 30/07/2018 00:00

I know this is because of alphabetical sorting. Wondering how I can customize sorting order with my date format (dd/mm/yyyy hh:mm) and also in descending order?

Upvotes: 1

Views: 5016

Answers (2)

Atif AbbAsi
Atif AbbAsi

Reputation: 6035

instead of date try saving milli seconds and then simple use query like below.or simply query on date.

Query Using Millis

databaseReference.orderByChild("newsDate").startAt(new DateTime().getMillis())

Query Using Date

databaseReference.orderByChild("newsDate").startAt(new DateTime())

Or

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String currentDateandTime = sdf.format(new Date());

databaseReference.orderByChild("newsDate").startAt(currentDateandTime )

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 138804

Wondering how I can customize sorting order with my date format (dd/mm/yyyy hh:mm)?

You can solve this by changing the type of your newsDate property from String to timpestamp. Please take a look at my answer from this post to see how you can achieve this.

and also in descending order?

To solve this, please see Frank van Puffelen's answer from this post.

Upvotes: 1

Related Questions