Introduction
In Java, the until() method of LocalDate class is used to get the amount of time until another date in terms of the specified unit. It calculates the amount of time between two LocalDate objects in terms of a single TemporalUnit. This method returns a long type value. The result will be negative if the end date is before the start date. This lab will demonstrate how to use the until() method of the LocalDate class in Java.
Create a new Java class
Create a new Java class named "LocalDateUntilMethod" in the ~/project directory, using the following command:
cd ~/project
touch LocalDateUntilMethod.java
Import the necessary packages
Import the necessary packages required to use the LocalDate class and the ChronoUnit enum using the following code:
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
Create a LocalDate object
Create a new LocalDate object to represent the start date using the LocalDate.of() method.
LocalDate localDate = LocalDate.of(2002, 01, 10);
Calculate the time difference between two dates using until() method
Calculate the amount of time between two LocalDate objects in terms of a single TemporalUnit, using the until() method. In this step, we will use the ChronoUnit enum to represent the unit. The below example demonstrates how to get years between two dates:
long period = localDate.until(LocalDate.of(2005,10,12), ChronoUnit.YEARS);
Similarly, the amount of days between two LocalDate objects can be calculated using the ChronoUnit.DAYS. The example below demonstrates how to get days between two dates:
long period = localDate.until(LocalDate.of(2005,10,12), ChronoUnit.DAYS);
Print the result
Print the result using the System.out.println() method. In this step, we can print the years or days between two dates.
System.out.println("Years : "+period);
System.out.println("Days : "+period);
Save and Compile the Java Program
Save the file by pressing CTRL+X, followed by Y, and then ENTER. Compile the Java program using the following command:
javac LocalDateUntilMethod.java
Run the Java Program
Run the Java program using the following command:
java LocalDateUntilMethod
The output will display the years or days between two dates, depending on the unit specified.
Summary
In this lab, you have learned how to use the until() method of the LocalDate class in Java. You have also learned how to calculate the time difference between two LocalDate objects in terms of a single TemporalUnit. By following these steps, you can now easily calculate the time difference between two dates in Java.



