Java LocalDateTime Compare: Using compareTo

In Java, the compareTo() method can be used to compare the size of LocalDateTime objects. This method returns an integer value representing the relationship between two LocalDateTime objects. If the first LocalDateTime object is earlier than the second one, a negative number is returned; if the first LocalDateTime object is later than the second one, a positive number is returned; if the two LocalDateTime objects are equal, then 0 is returned.

For example:

LocalDateTime dateTime1 = LocalDateTime.now();
LocalDateTime dateTime2 = LocalDateTime.of(2022, 1, 1, 12, 0);

int comparison = dateTime1.compareTo(dateTime2);

if (comparison < 0) {
    System.out.println("dateTime1 在 dateTime2 之前");
} else if (comparison > 0) {
    System.out.println("dateTime1 在 dateTime2 之后");
} else {
    System.out.println("dateTime1 和 dateTime2 相等");
}
bannerAds