Learn to compare two LocalDate instances to find out which date represents an older date in comparison to 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 provided methods which compare both date objects and return a boolean
value – true or false.
- 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.
import java.time.LocalDate; public class LocalDateComparison { public static void main(String[] args) { LocalDate nineApr = LocalDate.parse("2019-04-09"); LocalDate fourApr = LocalDate.parse("2019-04-04"); boolean isBefore = nineApr.isBefore(fourApr); System.out.println("nineApr is before fourApr :: " + isBefore); boolean isAfter = nineApr.isAfter(fourApr); System.out.println("nineApr is after fourApr :: " + isAfter); boolean isEqual = nineApr.isEqual(LocalDate.of(2019, 4, 9)); System.out.println("nineApr is equal to 04-09 :: " + isEqual); } }
Program output.
nineApr is before fourApr :: false nineApr is after fourApr :: true nineApr is equal to 04-09 :: true
2. LocalDate compareTo() method
The method
public int compareTo(ChronoLocalDate otherDate)
- 0 if both the dates represent the same date in calendar.
- positive integer if given date is later than the otherDate.
- negative integer if given date is earlier than the otherDate.
import java.time.LocalDate; public class LocalDateComparison { public static void main(String[] args) { LocalDate nineApr = LocalDate.parse("2019-04-09"); LocalDate fourApr = LocalDate.parse("2019-04-04"); int compareValue = nineApr.compareTo(fourApr); if(compareValue > 0) { System.out.println("nineApr is later than fourApr"); } else if (compareValue < 0) { System.out.println("nineApr is earlier than fourApr"); } else { System.out.println("both dates are equal"); } } }
Program output.
nineApr is later than fourApr
3. LocalDate equals() method
If we want to only check if both dates are equal of not (i.e. represent same calendar day or not), we can use
boolean equals(LocalDate otherDate)
- true – given date is same as otherDate.
- false – given date is NOT same as otherDate.
import java.time.LocalDate; public class LocalDateComparison { public static void main(String[] args) { System.out.println( LocalDate.parse("2019-04-09") .equals(LocalDate.of(2019, 4, 9)) ); //true System.out.println( LocalDate.parse("2019-04-09") .equals(LocalDate.of(2019, 1, 1)) ); //false } }
Program output.
true false
Happy Learning !!
Ref : LocalDate Java Doc