Learn to compare two LocalDate instances to find out which date represents an older date in comparison to the second date. LocalDate
class is part of java.time
package added in Java 8.
Method Name | Return Value | When to Use |
---|---|---|
isEqual() | boolean | To check if two dates are the same day in the calendar. |
isBefore() | boolean | To check if the first date is before the second date |
isAfter() | boolean | To check if the first date is after the second date |
compareTo() | int | To get a detailed comparison (negative, zero, positive) |
equals() | boolean | To check if two dates are the same day in the calendar (includes null check). |
isAfter()
, isBefore()
and isEqual()
Methods
1. The recommended way to compare two LocalDate objects is using one of the provided methods. These methods compare two localdate objects and return a boolean
value – true or false. These methods only consider the position of the two dates on the local timeline and do not consider the chronology, or calendar system.
- boolean isAfter(LocalDate other) – Checks if the specified date is after the other date.
- boolean isBefore(LocalDate other) – Checks if the specified date is before the other date.
- boolean isEqual(LocalDate other) – Checks if the specified date is equal to the other date.
LocalDate today = LocalDate.now();
LocalDate pastDate = LocalDate.parse("2022-01-04");
boolean isBefore = today.isBefore(pastDate); //false
boolean isAfter = today.isAfter(pastDate); //true
boolean isEqual = today.isEqual(LocalDate.of(2022, 1, 9)); //false
compareTo()
Method
2. LocalDate The method compareTo() compares two instances for the date-based values (day, month, year) and returns an integer value based on the comparison.
public int compareTo(ChronoLocalDate otherDate)
- 0 (Zero) if both the dates represent the same calendar date.
- Positive integer if the specified date is later than the otherDate.
- Negative integer if the specified date is earlier than the otherDate.
LocalDate today = LocalDate.now();
LocalDate pastDate = LocalDate.parse("2022-01-04");
int compareValue = today.compareTo(pastDate);
if (compareValue > 0) {
System.out.println("today is latter than 4th-Jan-2022");
} else if (compareValue < 0) {
System.out.println("today is earlier than 4th-Jan-2022");
} else {
System.out.println("both dates are equal");
}
equals()
Method
3. LocalDate If we want to only check if both dates are equal or not (i.e. represent the same calendar day or not), we can use equals() method.
The method boolean equals(LocalDate otherDate) returns:
- true – the specified date is same as otherDate.
- false – the specified date is NOT same as otherDate.
boolean isEqual = LocalDate.parse("2019-04-09")
.equals(LocalDate.of(2019, 4, 9)); //true
boolean isEqual = LocalDate.parse("2019-04-09")
.equals(LocalDate.of(2019, 1, 1)); //false
Happy Learning !!
Comments