Use the toEpochDay() method to calculate the difference between two dates
In this step, we will use the toEpochDay()
method to calculate the difference between two dates in days.
Add the following code to the main
method:
// Create two LocalDate objects
LocalDate date1 = LocalDate.of(2010, 5, 10);
LocalDate date2 = LocalDate.of(2020, 3, 15);
// Calculate the difference between the two dates in days
long diffInDays = date2.toEpochDay() - date1.toEpochDay();
// Print the difference in days
System.out.println("Difference in days: " + diffInDays);
Save and exit the file using Ctrl+X
, Y
, Enter
.
Recompile the program using the javac
command:
javac DateDemo.java
Run the program again using the java
command:
java DateDemo
This should output the difference between May 10, 2010 and March 15, 2020 in days.