Java program to calculate difference between two time periods

ht‮:spt‬//www.theitroad.com

Here's a Java program to calculate the difference between two time periods:

import java.time.Duration;
import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        LocalTime startTime = LocalTime.of(9, 0, 0);
        LocalTime endTime = LocalTime.of(13, 30, 0);

        Duration duration = Duration.between(startTime, endTime);

        long hours = duration.toHours();
        long minutes = duration.toMinutes() % 60;
        long seconds = duration.getSeconds() % 60;

        System.out.printf("Time difference: %d:%02d:%02d", hours, minutes, seconds);
    }
}

This program uses the LocalTime and Duration classes from the java.time package to calculate the difference between two time periods. We create two LocalTime objects representing the start and end times of the period we want to measure, and then use the Duration.between method to calculate the difference between these times.

We then use the toHours, toMinutes, and getSeconds methods of the Duration object to extract the hours, minutes, and seconds of the time difference, respectively. Finally, we print the time difference to the console in the format hh:mm:ss.

When you run this program, you will see output similar to the following:

Time difference: 4:30:00

Note that the LocalTime and Duration classes were introduced in Java 8, so this program requires Java 8 or later to run.