Compare Java LocalDate Objects Example

This example shows how to compare LocalDate objects in Java with an example.

LocalDate represents a year-month-day in the ISO calendar and is useful for representing a date without a time. You might use a LocalDate to track a significant event, such as birth date or wedding date.

Read more about LocalDate class with an example at https://www.javaguides.net/2018/08/java-8-localdate-class-api-guide.html.

Compare Java LocalDate Objects Example 

The LocalDate class provides below APIs to compare LocalDate objects in Java.
  • boolean isAfter(ChronoLocalDate other) - Checks if this date is after the specified date.
  • boolean isBefore(ChronoLocalDate other) - Checks if this date is before the specified date.
  • boolean isEqual(ChronoLocalDate other) - Checks if this date is equal to the specified date.
import java.time.LocalDate;
import java.time.Month;
/**
 * Program to demonstrate LocalDate Class APIs.
 * @author javaguides.net
 *
 */
public class LocalDateExamples {
 
    public static void main(String[] args) {
        compareLocalDate();
    }

    private static void compareLocalDate() {
        LocalDate localDate1 = LocalDate.now();
        LocalDate localDate2 = LocalDate.of(2017, Month.MAY, 14);
        LocalDate localDate3 = LocalDate.of(2016, Month.MAY, 15);

        // isEqual() example
        if (localDate1.isEqual(localDate2)) {
            System.out.println("localDate1 and localDate2 are equal");
        } else {
            System.out.println("localDate1 and localDate2 are not equal");
        }   

        // ifAfter() example
        if (localDate2.isAfter(localDate3)) {
            System.out.println("localDate2 comes after localDate3");
        }

        // isBefore() example
        if (localDate3.isBefore(localDate1)) {
           System.out.println("localDate3 comes before localDate1");
        }
    }
}
Output:
localDate1 and localDate2 are not equal
localDate2 comes after localDate3
localDate3 comes before localDate1

Reference


Comments