How can Java compare two dates to determine which is larger?

In Java, you can use either the Date class or the LocalDate class to compare two dates.

Utilize the Date class.

Date date1 = new Date();
Date date2 = new Date();

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");
}

Utilize the LocalDate class:

LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.now();

if (date1.isAfter(date2)) {
    System.out.println("date1 is after date2");
} else if (date1.isBefore(date2)) {
    System.out.println("date1 is before date2");
} else {
    System.out.println("date1 is equal to date2");
}

Note: When using the Date class for date comparison, it compares the milliseconds of the date and time. LocalDate class, on the other hand, only includes the date part and not the time part.

bannerAds