0

I have a list of objects that I want to sort according to their "date" attribute. Each object has a Date attribute which specifies its age. How can I sort these objects from the newest to the oldest? I heard of Comparator but I don't know if it applies to dates.

Can somebody help me figure out how to do that?

NissimL
  • 148
  • 8
Hubert Solecki
  • 2,611
  • 5
  • 31
  • 63
  • It does. Your comparator should simply take two dates and return appropriate values if one is before the other – kolossus Jul 29 '14 at 14:50
  • Date myDate1 = new Date(); Date myDate2 = new Date(); myDate1.compare(myDate2) will return a value between -1 and 1 to indicate with one if for the other or if they are equals (0). – Rene M. Jul 29 '14 at 14:53
  • the accepted answer for the duplicated question addresses this exact case. – Nathan Hughes Jul 29 '14 at 14:55

2 Answers2

0

You can use the various methods of before(), after(), compareTo(), or convert the value into a Long and then compare that instead.

http://docs.oracle.com/javase/6/docs/api/java/util/Date.html

David Tran
  • 16
  • 2
0

You can convert date into timestamp and sort it. It is very easy for sorting.

Prashant Gurav
  • 505
  • 7
  • 17