ChronoLocalDateTime compareTo() method in Java with Examples
The compareTo()
method is used to compare two ChronoLocalDateTime
objects for order. It returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Syntax:
public int compareTo(ChronoLocalDateTime<?> other)
Parameters:
- other
: the other ChronoLocalDateTime
to compare to, not null.
Returns:
- a negative integer if this ChronoLocalDateTime
is less than other
.
- zero if this ChronoLocalDateTime
is equal to other
.
- a positive integer if this ChronoLocalDateTime
is greater than other
.
Examples:
- Comparing two
ChronoLocalDateTime
objects usingcompareTo()
method:
import java.time.LocalDateTime;
import java.time.chrono.ChronoLocalDateTime;
public class Example {
public static void main(String[] args) {
LocalDateTime dateTime1 = LocalDateTime.of(2021, 10, 1, 10, 30);
LocalDateTime dateTime2 = LocalDateTime.of(2021, 10, 1, 11, 30);
ChronoLocalDateTime<?> chronoDateTime1 = dateTime1;
ChronoLocalDateTime<?> chronoDateTime2 = dateTime2;
int result = chronoDateTime1.compareTo(chronoDateTime2);
if (result < 0) {
System.out.println(dateTime1 + " is before " + dateTime2);
} else if (result == 0) {
System.out.println(dateTime1 + " is equal to " + dateTime2);
} else {
System.out.println(dateTime1 + " is after " + dateTime2);
}
}
}
Output:
2021-10-01T10:30 is before 2021-10-01T11:30
- Comparing two
ChronoLocalDateTime
objects of different chronologies usingcompareTo()
method:
import java.time.LocalDateTime;
import java.time.chrono.HijrahDate;
import java.time.chrono.IsoChronology;
import java.time.chrono.ChronoLocalDateTime;
public class Example {
public static void main(String[] args) {
LocalDateTime dateTime = LocalDateTime.of(2021, 10, 1, 10, 30);
HijrahDate hijrahDate = HijrahDate.from(dateTime);
ChronoLocalDateTime<?> chronoDateTime1 = dateTime;
ChronoLocalDateTime<?> chronoDateTime2 = hijrahDate.atTime(10, 30);
int result = chronoDateTime1.compareTo(chronoDateTime2);
if (result < 0) {
System.out.println(dateTime + " is before " + hijrahDate);
} else if (result == 0) {
System.out.println(dateTime + " is equal to " + hijrahDate);
} else {
System.out.println(dateTime + " is after " + hijrahDate);
}
}
}
Output:
2021-10-01T10:30 is after AH 1443-02-22T10:30 (Hijrah calendar)