Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet83/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   79   80   81   82   83   84   85   86   ...   245
Bog'liq
Java 17 Recipes

4-14. Comparing Two Dates
 Problem
You want to determine whether one date is greater than another.
Chapter 4 Numbers aNd dates


137
 Solution
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);
}
}
Similarly, there are convenience methods for use when performing date comparison. 
Specifically, the isAfter(), isBefore(), and isEqual() methods can compare in the 
same manner as compareTo(), as seen in the following example.
public static void compareDates2(LocalDate ldt1, LocalDate ldt2){
if(ldt1.isAfter(ldt2)){
System.out.println(ldt1 + " is after " + ldt2);
} else if (ldt1.isBefore(ldt2)){
System.out.println(ldt1 + " is before " + ldt2);
} else if (ldt1.isEqual(ldt2)){
System.out.println(ldt1 + " is equal to " + ldt2);
}
}
The main is:
public static void main(String[] args) {
LocalDate anniversary = LocalDate.of(2000,
Month.NOVEMBER, 11);
LocalDate today = LocalDate.now();
compareDates(anniversary, today);
Chapter 4 Numbers aNd dates


138
compareDates2(anniversary, anniversary);
}
The output is:
2000-11-11 is before 2021-11-30
2000-11-11 is equal to 2000-11-11
 How It Works
Many of the Date-Time API classes contain a method that compares two different date- 
time objects. In the solution to this example, the LocalDate.compareTo() method 
determines if one LocalDate object is greater than another. The compareTo() method 
returns a negative int value if the first LocalDate object is greater than the second, a zero 
if they are equal, and a positive number if the second LocalDate object is greater than 
the first. Each of the date-time classes that contain compareTo() has the same outcome. 
An int value is returned indicating if the first object is greater than, less than, or equal to 
the second.
As seen in the second example, the isAfter(), isBefore(), and isEqual() 
methods can also be used for comparison purposes. These methods return a boolean 
to indicate the comparison results. While the outcome of these methods can perform 
date comparison in much the same way as compareTo(), they can make code a bit easier 
to read.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   79   80   81   82   83   84   85   86   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling