Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to compare two dates

Short answer

Use isBefore(), isAfter() and isEqual():

void main() {
    var deadline = LocalDate.of(2026, 3, 31);
    var today = LocalDate.of(2026, 3, 8);
 
    IO.println(today.isBefore(deadline));
    IO.println(today.isAfter(deadline));
    IO.println(today.isEqual(LocalDate.of(2026, 3, 8)));
}

Output:

true
false
true

Within a range

Check both bounds. The !isBefore condition includes the start day:

boolean inRange(LocalDate date, LocalDate from, LocalDate to) {
    return !date.isBefore(from) && !date.isAfter(to);
}
 
void main() {
    var from = LocalDate.of(2026, 7, 1);
    var to = LocalDate.of(2026, 7, 14);
 
    IO.println(inRange(LocalDate.of(2026, 7, 1), from, to));
    IO.println(inRange(LocalDate.of(2026, 7, 15), from, to));
}

Output:

true
false

Sorting

Dates implement Comparable, so they sort without a comparator:

void main() {
    var dates = new ArrayList<>(List.of(
            LocalDate.of(2026, 5, 1), LocalDate.of(2025, 12, 31), LocalDate.of(2026, 1, 15)));
    Collections.sort(dates);
 
    IO.println(dates);
    IO.println(Collections.max(dates));
}

Output:

[2025-12-31, 2026-01-15, 2026-05-01]
2026-05-01

Date and time

To compare only the dates of LocalDateTime values, take toLocalDate():

void main() {
    var a = LocalDateTime.of(2026, 3, 8, 9, 0);
    var b = LocalDateTime.of(2026, 3, 8, 18, 30);
 
    IO.println(a.isEqual(b));
    IO.println(a.toLocalDate().isEqual(b.toLocalDate()));
}

Output:

false
true

Common mistake

Comparing dates with ==. Two equal dates can be different objects:

void main() {
    var a = LocalDate.parse("2026-03-08");
    var b = LocalDate.of(2026, 3, 8);
 
    IO.println(a == b);
    IO.println(a.equals(b));
}

Output:

false
true

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.