Java Calculate Number of Seconds Between two LocalTime

Tags: Java LocalTime ChronoUnit Java 8

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

How to get number of seconds between two LocalTime

In Java, we can use the ChronoUnit.SECONDS.between() method to calculate the number of seconds between two LocalTime values as the following example Java program.

SecondsBetweenLocalTimExample.java

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

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

        // Calculate Number of Seconds Between two LocalTime
        long numberOfSeconds = ChronoUnit.SECONDS.between(startTime, endTime);

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

Happy Coding 😊

Java Calculate Number of Hours Between two LocalTime

Java Calculate Number of Minutes Between two LocalTime

Java Calculate Number of Milliseconds Between two LocalTime

Java Calculate Number of Nanoseconds Between two LocalTime