0

I have a sort on an ArrayList; matchesList.sort(Comparator.comparing(matches::getDate).thenComparing(matches::getTime));

The value comes from a Firebase database so the value is stored as a String instead of Date (I don't want to have to store the date value as long format) in the following format; dd/MM/yyyy

The sort above does not work as expected, I'm guessing after reading through other posts that this is due to the comparator not knowing what the String date value actually means so cannot sort it as expected.

After some reading and playing around with, ideally I'd like to convert the class that defines my ArrayList structure to support the Date type but when trying this I get an error about cannot convert a string value to date when looping the dataset and trying to populate the ArrayList;

matches match = matchSnapshot.getValue(matches.class);

Again another post talks about this being due to Firebase not supporting Date types, but I've also tried using *.toString on Date type variables and still it doesn't like this.

My question is; is there a way to store the date format dd/MM/yyyy as String and then to cast that to date that can be added to an ArrayList?

Carl Bruiners
  • 87
  • 3
  • 11
  • add your own method inside your class for return the date from your string – Rajasekaran M Apr 07 '18 at 13:18
  • Contrary to your Question's remark: [According to this](https://firebase.google.com/docs/firestore/manage-data/data-types), Firebase offers a `Date and time` data type that offers chronological sorting. – Basil Bourque Jun 26 '19 at 02:07

2 Answers2

2

I would suggest you to cast your dd/MM/yyyy format String to timestamp (long) and then sorting timestamps (you can use Collections.sort() for that). More on timestamps here: Convert string Date into timestamp in Android?

Then, when you need to use those sorted values again, just cast them back to date. More about this here: Convert timestamp into string Date in Android?


Hope it helps.
Tomas Jablonskis
  • 4,246
  • 4
  • 22
  • 40
2

Add your own Comparator and use the other comparing() method.

matchesList.sort(Comparator.comparing(matches::getDate, myComparator).thenComparing(matches::getTime));

Because the date format you are using does not sort naturally, it's not going to be able to do it properly. I don't know of any date comparator that's readily available in a standard library, so probably best to just write your own.

class DateComparator implements Comparator<String> {
    @Override
    public int compare(String date1, String date2) {
        // TODO: compare your date strings
    }
}
SaxyPandaBear
  • 377
  • 1
  • 6