Compare Two Dates in Java
Problem
Dates have a natural order on the calendar, so two LocalDate values can be compared to see which comes first.
Given a deadline of 30 June 2026 and a submission on 2 July 2026, decide whether the submission was on time.
Java Program
import java.time.LocalDate;
public class CompareDates {
public static void main(String[] args) {
LocalDate deadline = LocalDate.of(2026, 6, 30);
LocalDate submitted = LocalDate.of(2026, 7, 2);
System.out.println("Submitted before deadline? " + submitted.isBefore(deadline));
System.out.println("Submitted after deadline? " + submitted.isAfter(deadline));
System.out.println("Same day? " + submitted.isEqual(deadline));
System.out.println("compareTo result: " + submitted.compareTo(deadline)); // > 0 means later
if (submitted.isAfter(deadline)) {
System.out.println("Status: late");
} else {
System.out.println("Status: on time");
}
}
}Output
Core Logic
LocalDate provides readable comparison methods that each return a boolean, plus compareTo for sorting.
- 1
submitted.isBefore(deadline)is false andisAfteris true. - 2
isEqualchecks for the same calendar day. - 3
compareToreturns a negative number, zero or a positive number, like anyComparable. - 4An
ifonisAfterdecides the final status.
Key Point: Only rely on the sign of compareTo, not its exact value — the spec promises negative, zero or positive, nothing more.
Key Concepts
Approach 2: Sorting a List of Dates
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SortDates {
public static void main(String[] args) {
List<LocalDate> dates = new ArrayList<>(Arrays.asList(
LocalDate.of(2026, 7, 2),
LocalDate.of(2025, 12, 25),
LocalDate.of(2026, 6, 30),
LocalDate.of(2026, 1, 1)));
Collections.sort(dates); // LocalDate implements Comparable, oldest first
System.out.println("Oldest first: " + dates);
dates.sort(Collections.reverseOrder());
System.out.println("Newest first: " + dates);
System.out.println("Latest date: " + Collections.max(dates));
}
}
Output
Core Logic
Because LocalDate implements Comparable, the standard collection utilities can sort dates and find extremes directly.
- 1
Collections.sort(dates)orders the dates oldest first. - 2
dates.sort(Collections.reverseOrder())flips them to newest first. - 3
Collections.maxreturns the latest date.
Key Point: Never sort dates as strings in day-first formats such as 02/07/2026 — text order and calendar order disagree; keep them as LocalDate until display.
Key Concepts
Interview Questions
Should you use equals or isEqual?
For two LocalDate values they agree. For ZonedDateTime values, equals also compares the zone, while isEqual compares only the instant.
How do you check whether a date is in a range?
!date.isBefore(start) && !date.isAfter(end) includes both ends of the range.