In Java, a.compareTo(b) compares two LocalDateTime objects. The result is negative if a is earlier than b, zero if they are the same, and positive if a is later.
Because LocalDateTime implements Comparable, this is the method that sorting and sorted collections use behind the scenes. It compares the date first, and then the time of day.
An instance method of java.time.LocalDateTime (since Java 8): call it on a LocalDateTime object. Add import java.time.LocalDateTime; at the top of your file. It comes from Comparable and ChronoLocalDateTime, which LocalDateTime implements.
Syntax
Call it on one date-time and pass the other. Only look at whether the answer is below, equal to, or above zero.
Java
LocalDateTime early = LocalDateTime.of(2026, 3, 15, 9, 0);
LocalDateTime late = LocalDateTime.of(2026, 3, 15, 17, 30);
int result = early.compareTo(late); // negative: early comes first
boolean isEarlier = result < 0; // true
Call
What it does
a.compareTo(b)
Negative, zero, or positive, depending on the order of a and b.
a.isBefore(b)
A clearer way to ask "is a earlier than b?".
a.isAfter(b)
A clearer way to ask "is a later than b?".
Collections.sort(list)
Sorts a list of date-times, using compareTo().
Do not test the result against -1 or 1. Only the sign is promised.
Library declarations
Java
// java.time.LocalDateTime
public int compareTo(ChronoLocalDateTime<?> other)
Parameters
Parameter
Description
other (ChronoLocalDateTime<?>)
The date-time to compare with. It must not be null.
Return Value
Return Value
Description
int
A negative number if this is earlier, zero if equal, a positive number if this is later.