Calculating the Difference Between Two Time Periods in Java
In many real-world applications, such as attendance tracking or scheduling systems, you may need to measure the time elapsed between two timestamps.
Java offers a powerful java.time
package to handle date and time operations effectively.
In this article, we’ll demonstrate how to compute the difference between two time periods in Java.
This tutorial is a continuation of the concept described in our C language lead article, but adapted to Java's modern time-handling features.
Required Imports
For this program, we’ll need:
import java.time.LocalDateTime;
import java.time.Duration;
Note: These classes allow us to represent date-time values and compute the duration between them.
Java Program: Calculate the Difference Between Two Time Periods
// DIFFERENCE BETWEEN TWO TIME PERIODS in Java using LocalDateTime
import java.util.Scanner;
import java.time.LocalDateTime;
import java.time.Duration;
public class Main {
public static void main(String[] args) {
// Step-1 Define two LocalDateTime objects
LocalDateTime startTime = LocalDateTime.of(2025, 5, 1, 10, 30, 0);
LocalDateTime endTime = LocalDateTime.of(2025, 5, 9, 15, 45, 0);
// Step-2 Calculate duration between the two time periods
Duration duration = Duration.between(startTime, endTime);
// Step-3 Extract hours, minutes, and seconds from the duration
long totalSeconds = duration.getSeconds();
long hours = totalSeconds / 3600;
long minutes = (totalSeconds % 3600) / 60;
long seconds = totalSeconds % 60;
// Step-4 Display the result
System.out.println("\nTIME DIFFERENCE: " + hours + " HOURS, " + minutes + " MINUTES, " + seconds + " SECONDS");
}
}
Output
TIME DIFFERENCE: 205 HOURS, 15 MINUTES, 0 SECONDS
Explanation
In this Java program:
-
We use
LocalDateTime
to set the starting and ending points. -
The
Duration.between()
method computes the total difference in seconds. -
From that total, we calculate the number of hours, minutes, and seconds.
-
The final output represents the precise difference in a human-readable format.
This approach is both precise and readable, making use of Java 8’s modern time-handling features.