Introduction
In this lab, you will learn how to use the compareTo()
method from the LocalDate class in Java. This method is used to compare two different dates and returns an integer value.
In this lab, you will learn how to use the compareTo()
method from the LocalDate class in Java. This method is used to compare two different dates and returns an integer value.
Add the following import statement at the beginning of the file to import the LocalDate class:
import java.time.LocalDate;
In this step, you will compare two different dates using the compareTo()
method and display the output based on the comparison. Add the following code to the main() method:
// Take a date
LocalDate date1 = LocalDate.of(2021, 12, 31);
// Displaying date
System.out.println("Date 1 is : "+date1);
// Take another date
LocalDate date2 = LocalDate.now();
// Displaying date
System.out.println("Date 2 is : "+date2);
// Comparing two dates using compareTo()
int result = date1.compareTo(date2);
// Display whether date 1 is before, after or equals to date 2
if(result<0){
System.out.println("Date 1 is before Date 2");
}
else if(result>0){
System.out.println("Date 1 is after Date 2");
}
else{
System.out.println("Both Dates are same");
}
Save the file and run the following command in the terminal:
javac DateComparator.java && java DateComparator
In this step, you will change the dates used for comparison and see the output. Replace the following line in the code:
LocalDate date1 = LocalDate.of(2021, 12, 31);
With any other date and rerun the code.
In this step, you will change the dates used for comparison to be the same. Replace the following line in the code:
LocalDate date2 = LocalDate.now();
With the same date as date1
and rerun the code.
In this step, you will compare today's date with a future date. Replace the following line in the code:
LocalDate date1 = LocalDate.of(2021, 12, 31);
With any date in the future and rerun the code.
In this step, you will compare today's date with a past date. Replace the following line in the code:
LocalDate date1 = LocalDate.of(2021, 12, 31);
With any date in the past and rerun the code.
In this step, you will use a different object that extends from ChronoLocalDate
rather than LocalDate
and compare two different dates. First, create a new class named MyDate
and add the following code:
import java.time.chrono.ChronoLocalDate;
public class MyDate implements ChronoLocalDate {
// Add implementation details for ChronoLocalDate interface
// ...
}
Then, replace the LocalDate
variables with MyDate
variables and adjust the implementation details for the MyDate
class as necessary. Rerun the code to ensure it still works.
In this lab, you have learned how to compare different dates in Java using the compareTo()
method from the LocalDate class. You have also learned how to display output based on the result of the comparison, as well as how to modify the code for different test cases.