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.
1. isAfter()
, isBefore()
and isEqual()
Methods
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 given date is after the other date.
- boolean isBefore(LocalDate other) – Checks if given date is before the other date.
- boolean isEqual(LocalDate other) – Checks if given date is equals 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
2. LocalDate compareTo()
Method
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 date in calendar.
- Positive integer if given date is latter than the otherDate.
- Negative integer if given 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");
}
3. LocalDate equals()
Method
If we want to only check if both dates are equal or not (i.e. represent same calendar day or not), we can use equals() method.
The method boolean equals(LocalDate otherDate) returns:
- true – given date is same as otherDate.
- false – given date is NOT same as otherDate.
boolean isEqual = LocalDate.parse("2019-04-09")
.equals(LocalDate.of(2019, 4, 9)); //true
loolean isEqual = LocalDate.parse("2019-04-09")
.equals(LocalDate.of(2019, 1, 1)); //false
Happy Learning !!