Using Date.compareTo() function:
A classic method to compare two java.util.Date in Java.
Return value is 0 if both dates are equal.
Return value is greater than 0 , if Date is after the date argument.
Return value is less than 0, if Date is before the date argument
TestDate.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDate {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2019-08-03");
Date date2 = sdf.parse("2019-07-31");
System.out.println("date1 : " + sdf.format(date1));
System.out.println("date2 : " + sdf.format(date2));
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 if (date1.compareTo(date2) == 0) {
System.out.println("Date1 is equal to Date2");
} else {
System.out.println("How to get here?");
}
}
}
Output:
date1 : 2019-08-03
date2 : 2019-07-31
Date1 is after Date2