But i couldn't able to sort the date in descending order.
Two easy options:
- You could just reverse your comparison yourself, using
secondDate.compareTo(firstDate). (I assume that in your real code you're actually returningretVal; it's ignored in your posted code.) - Call
Collections.reverseOrder(Comparator)to create a comparator with the reverse order of the original one.
But i couldn't able to sort the date in descending order.
Two easy options:
- You could just reverse your comparison yourself, using
secondDate.compareTo(firstDate). (I assume that in your real code you're actually returningretVal; it's ignored in your posted code.) - Call
Collections.reverseOrder(Comparator)to create a comparator with the reverse order of the original one.
Instead of comparing firstDate against secondDate, compare secondDate against firstDate:
retVal = secondDate.compareTo(firstDate);
And don't forget to return retVal instead of 0 ;)
You can use Comparator.reverseOrder() to have a comparator giving the reverse of the natural ordering.
If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed().
Sample code:
Stream.of(1, 4, 2, 5)
.sorted(Comparator.reverseOrder());
// stream is now [5, 4, 2, 1]
Stream.of("foo", "test", "a")
.sorted(Comparator.comparingInt(String::length).reversed());
// stream is now [test, foo, a], sorted by descending length
You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:
Comparator<SomeEntity> ENTITY_COMPARATOR =
Comparator.comparing(SomeEntity::getProperty1, Comparator.reverseOrder())
.thenComparingInt(SomeEntity::getProperty2)
.thenComparing(SomeEntity::getProperty3, Comparator.reverseOrder());
Date has before and after methods and can be compared to each other as follows:
if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
// In between
}
For an inclusive comparison:
if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
/* historyDate <= todayDate <= futureDate */
}
You could also give Joda-Time a go, but note that:
Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310).
Back-ports are available for Java 6 and 7 as well as Android.
Use compareTo:
date1.compareTo(date2);