We can make use of the isBefore(), isAfter() and, isEqual() methods to compare two dates in Java of type java.time.LocalDate.
Example 1: Compare if two dates are equal
LocalDate date1 = LocalDate.of(2023, 10, 18);
LocalDate date2 = LocalDate.of(2023, 10, 19);
boolean isEqual = date1.isEqual(date2);
Example 2: Check if one date is before another
LocalDate date1 = LocalDate.of(2023, 10, 18);
LocalDate date2 = LocalDate.of(2023, 10, 19);
boolean isEqual = date1.isBefore(date2);
Example 3: Check if one date is after another
LocalDate date1 = LocalDate.of(2023, 10, 18);
LocalDate date2 = LocalDate.of(2023, 10, 19);
boolean isEqual = date1.isAfter(date2);
Now let's combine this code with a if-else ladder.
package org.code2care.examples;
import java.time.LocalDate;
/**
* Compare two dates in Java
*
* Author: code2care.org
*
*/
public class DateComparisonExample {
public static void main(String... args) {
LocalDate date1 = LocalDate.of(2023, 10, 18);
LocalDate date2 = LocalDate.of(2023, 10, 19);
if (date1.isEqual(date2)) {
System.out.println(date1 + " is equal to " + date2);
} else if (date1.isBefore(date2)) {
System.out.println(date1 + " is before " + date2);
} else {
System.out.println(date1 + "is after" + date2);
}
}
}

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!