How to Compare Two Dates in Java?


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);
        }
    }
}
Compare two dates in Java Example Output
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap