How can Java calculate the difference in time between two time values?

In Java, the java.time.Duration class can be used to calculate the time difference between two times. Here is an example code:

import java.time.Duration;
import java.time.LocalDateTime;

public class TimeDifferenceCalculator {
    public static void main(String[] args) {
        LocalDateTime startTime = LocalDateTime.of(2022, 1, 1, 10, 0, 0);
        LocalDateTime endTime = LocalDateTime.of(2022, 1, 1, 12, 30, 0);

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

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

        System.out.println("时间差:" + hours + "小时 " + minutes + "分钟 " + seconds + "秒");
    }
}

In the above example, we used the LocalDateTime class to create two time points, startTime and endTime. We then used the Duration.between method to calculate the time difference between the two points and stored the result in the duration variable.

Next, we can utilize methods in the Duration class such as toHours, toMinutes, and getSeconds to convert the time difference into hours, minutes, and seconds.

Finally, we will print the values of hours, minutes, and seconds to display the time difference.

bannerAds