# LocalDateTime until() Method in Java

Java 8Object Oriented ProgrammingProgramming

The difference between two LocalDateTime objects can be obtained using the until() method in the LocalDateTime class in Java. This method requires two parameters i.e. the end date for the LocalDateTime object and the Temporal unit. Also, it returns the difference between two LocalDateTime objects in the Temporal unit specified.

A program that demonstrates this is given as follows −

## Example

Live Demo

import java.time.*;
import java.time.temporal.*;
public class Demo {
public static void main(String[] args) {
LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
LocalDateTime ldt2 = LocalDateTime.parse("2019-02-19T12:21:30");
System.out.println("The first LocalDateTime is: " + ldt1);
System.out.println("The second LocalDateTime is: " + ldt2);
System.out.println("\nThe difference between two LocalDateTimes in hours is: " + ldt1.until(ldt2, ChronoUnit.HOURS));
}
}

## Output

The first LocalDateTime is: 2019-02-18T23:15:30
The second LocalDateTime is: 2019-02-19T12:21:30
The difference between two LocalDateTimes in hours is: 13

Now let us understand the above program.

First the two LocalDateTime objects are displayed. Then the difference between them in hours is obtained using the until() method and displayed. A code snippet that demonstrates this is as follows −

LocalDateTime ldt1 = LocalDateTime.parse("2019-02-18T23:15:30");
LocalDateTime ldt2 = LocalDateTime.parse("2019-02-19T12:21:30");
System.out.println("The first LocalDateTime is: " + ldt1);
System.out.println("The second LocalDateTime is: " + ldt2);
System.out.println("\nThe difference between two LocalDateTimes in hours is: " + ldt1.until(ldt2, ChronoUnit.HOURS));
Updated on 30-Jul-2019 22:30:25