Java Reference
In-Depth Information
Utilize one of the compareTo() methods that are part of the Date-Time API classes.
In the following solution, two LocalDate objects are compared and an appropriate
message is displayed.
public static void compareDates(LocalDate ldt1,
LocalDate ldt2) {
int comparison = ldt1.compareTo(ldt2);
if (comparison > 0) {
System.out.println(ldt1 + " is larger than "
+ ldt2);
} else if (comparison < 0) {
System.out.println(ldt1 + " is smaller than "
+ ldt2);
} else {
System.out.println(ldt1 + " is equal to "
+ ldt2);
}
}
How It Works
Many of the Date-Time API classes contain a method that is used to compare two dif-
ferent date-time objects. In the solution to this example, the
LocalDate.compareTo() method is used to determine if one LocalDate object
is greater than another. The compareTo() method returns a negative int value if
the first LocalDate is greater than the second, a zero if they are equal, and a positive
number if the second LocalDate is greater than the first.
Each of the date-time classes that contain a compareTo() has the same outcome.
That is, an int value is returned indicating if the first object is greater than, less than,
or equal to the second. Each of the classes that contains the compareTo() method is
listed here:
Duration
LocalDate
LocalDateTime
Search WWH ::




Custom Search