Calculate Time Difference Between Two Times in Java
Problem
A Duration measures an amount of time in seconds and nanoseconds, independent of any calendar.
Given a check-in at 09:15 and a check-out at 17:40:30, calculate how long the person worked.
Java Program
import java.time.Duration;
import java.time.LocalTime;
public class TimeDifferenceDuration {
public static void main(String[] args) {
LocalTime checkIn = LocalTime.of(9, 15);
LocalTime checkOut = LocalTime.of(17, 40, 30);
Duration worked = Duration.between(checkIn, checkOut);
System.out.println("Duration: " + worked); // ISO form, e.g. PT8H25M30S
System.out.println("Hours: " + worked.toHours());
System.out.println("Minutes part: " + worked.toMinutesPart()); // Java 9+
System.out.println("Seconds part: " + worked.toSecondsPart());
System.out.println("Total minutes: " + worked.toMinutes());
}
}Output
Core Logic
Duration.between gives the exact gap, and its methods break it into whole units or report the total in one unit.
- 1Both times are
LocalTimevalues. - 2
Duration.between(checkIn, checkOut)computes the difference. - 3
toHours()gives whole hours;toMinutesPart()andtoSecondsPart()(Java 9) give the remainders. - 4
toMinutes()gives the whole duration in minutes.
PT8H25M30S means 8 hours, 25 minutes and 30 seconds.Key Point: toMinutes() is the total (505), while toMinutesPart() is only the minutes after the whole hours (25).
Key Concepts
Approach 2: Shifts That Cross Midnight
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class TimeDifferenceOvernight {
public static void main(String[] args) {
LocalTime start = LocalTime.of(22, 0);
LocalTime end = LocalTime.of(6, 30);
System.out.println("Naive LocalTime difference: " + Duration.between(start, end)); // negative!
LocalDateTime s = LocalDateTime.of(2026, 3, 9, 22, 0);
LocalDateTime e = LocalDateTime.of(2026, 3, 10, 6, 30); // the next morning
Duration shift = Duration.between(s, e);
System.out.printf("Night shift: %d h %d min%n", shift.toHours(), shift.toMinutesPart());
}
}
Output
Core Logic
A time of day alone can't tell that 06:30 is the next morning, so overnight gaps need full date-times.
- 1
Duration.between(22:00, 06:30)withLocalTimereturns a negative duration. - 2Using
LocalDateTimevalues on consecutive days gives the real 8½ hours. - 3The result is printed as hours and minutes.
Key Point: If only times are available, add 24 hours when the end is earlier than the start.
Key Concepts
Interview Questions
What's the difference between Duration and Period?
Duration measures exact time in seconds and nanoseconds; Period measures calendar amounts in years, months and days.
How do you format a Duration as hh:mm:ss?
String.format("%02d:%02d:%02d", d.toHours(), d.toMinutesPart(), d.toSecondsPart()).