LocalTime until() Method in Java


The difference between two LocalTime objects can be obtained using the until() method in the LocalTime class in Java. This method requires two parameters i.e. the end time for the LocalTime object and the Temporal unit. Also, it returns the difference between two LocalTime 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) {
      LocalTime lt1 = LocalTime.parse("10:15:30");
      LocalTime lt2 = LocalTime.parse("12:21:30");
      System.out.println("The first LocalTime is: " + lt1);
      System.out.println("The second LocalTime is: " + lt2);
      System.out.println("
The difference between two LocalTimes in hours is: " + lt1.until(lt2, ChronoUnit.HOURS));    } }

Output

The first LocalTime is: 10:15:30
The second LocalTime is: 12:21:30
The difference between two LocalTimes in hours is: 2

Now let us understand the above program.

First the two LocalTime 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 −

LocalTime lt1 = LocalTime.parse("10:15:30");
LocalTime lt2 = LocalTime.parse("12:21:30");
System.out.println("The first LocalTime is: " + lt1);
System.out.println("The second LocalTime is: " + lt2);
System.out.println("
The difference between two LocalTimes in hours is: " + lt1.until(lt2, ChronoUnit.HOURS));

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements