How to compare dates in Java? [duplicate]
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.
Following are most common way of comparing dates
(my preference is Approach 1):
Approach 1: Using Date.before()
, Date.after()
and Date.equals(
)
if (date1.after(date2)) { System.out.println("Date1 is after Date2");}if (date1.before(date2)) { System.out.println("Date1 is before Date2");}if (date1.equals(date2)) { System.out.println("Date1 is equal Date2");}
Approach 2: Date.compareTo()
if (date1.compareTo(date2) > 0) { System.out.println("Date1 is after Date2");} else if (date1.compareTo(date2) < 0) { System.out.println("Date1 is before Date2");} else { System.out.println("Date1 is equal to Date2");}
Approach 3: Calender.before()
, Calender.after(
) and Calender.equals()
Calendar cal1 = Calendar.getInstance();Calendar cal2 = Calendar.getInstance();cal1.setTime(date1);cal2.setTime(date2);if (cal1.after(cal2)) { System.out.println("Date1 is after Date2");}if (cal1.before(cal2)) { System.out.println("Date1 is before Date2");}if (cal1.equals(cal2)) { System.out.println("Date1 is equal Date2");}