Java Calculate Number of Hours Between two LocalTime

Tags: Java LocalTime ChronoUnit Java 8

In this Java core tutorial, we learn how to calculate the number of hours between two LocalTime objects using the java.time.temporal.ChronoUnit class in Java programming language.

How to get number of hours between two LocalTime

In Java, with given start and end LocalTime values we can use the ChronoUnit.HOURS.between() method to calculate the number of hours between them as the following Java code.

HoursBetweenLocalTimeExample.java

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class HoursBetweenLocalTimeExample {
    public static void main(String... args) {
        LocalTime startTime = LocalTime.of(10, 20, 30);
        LocalTime endTime = LocalTime.of(23, 10, 40);

        // Calculate Number of Hours Between two LocalTime
        long numberOfHours = ChronoUnit.HOURS.between(startTime, endTime);

        System.out.println(String.format("Number of hours between %s and %s is %d", startTime, endTime, numberOfHours));
    }
}
The output as below.
Number of hours between 10:20:30 and 23:10:40 is 12

Happy Coding 😊

Java Calculate Number of Minutes Between two LocalTime

Java Calculate Number of Seconds Between two LocalTime

Java Calculate Number of Milliseconds Between two LocalTime

Java Calculate Number of Nanoseconds Between two LocalTime