Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

LocalDate.compareTo: ordering orders by date only

Use the sign of `LocalDate.compareTo` to order dates. In a date-only ordering, orders on the same day compare as equal even when they have different titles.

Version: Java SE 21

Syntax

import java.time.LocalDate;
import java.time.chrono.ChronoLocalDate;

// Instance method declared by LocalDate:
public int compareTo(ChronoLocalDate other)

// Call with a LocalDate receiver and a non-null ChronoLocalDate argument:
int result = date.compareTo(other);

The instance method LocalDate.compareTo takes a java.time.chrono.ChronoLocalDate argument, so you can pass another LocalDate. A java.time.LocalDate represents an ISO date without a time of day or time zone.

For two LocalDate values, a result < 0 means the receiver is earlier, == 0 means the same date, and > 0 means the receiver is later. Check the sign: a nonzero result need not be -1 or 1, and it is not a count of days. Passing null throws NullPointerException.

When comparing dates from different calendar systems, compareTo compares their days on the local timeline first. If they represent the same day, the chronology ID breaks the tie. Use isEqual to test for the same day regardless of chronology.

In the example, Order.compareTo compares only date; title is not a tie-breaker. Two orders with the same date but different titles compare as 0, even though the record's generated equals returns false. A TreeSet using this natural ordering would therefore not store both as separate elements.

Examples

import java.time.LocalDate;

public class Main {
    record Order(LocalDate date, String title) implements Comparable<Order> {
        @Override
        public int compareTo(Order other) {
            return date.compareTo(other.date());
        }
    }

    public static void main(String[] args) {
        var first = new Order(LocalDate.of(2025, 4, 2), "Zebra");
        var later = new Order(LocalDate.of(2025, 4, 5), "Alpha");
        var sameDay = new Order(LocalDate.of(2025, 4, 2), "Beta");

        System.out.println(Integer.signum(first.compareTo(later)));
        System.out.println(Integer.signum(later.compareTo(first)));
        System.out.println(Integer.signum(first.compareTo(sameDay)));
        System.out.println(first.equals(sameDay));
    }
}

Result

-1
1
0
false

`Integer.signum` normalizes the comparison results to `-1`, `1`, and `0`: earlier, later, and the same day. The final `false` tests record equality, not date ordering.

Related lessons

  • Java · Lesson 11 · Advanced · Version: 2

Sources