🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Java 程序:计算两个时间段之间的差异 > 原文: [https://www.programiz.com/java-programming/examples/difference-time](https://www.programiz.com/java-programming/examples/difference-time) #### 在此程序中,您将学习计算 Java 中两个时间段之间的时差。 ## 示例:计算两个时间段之间的差异 ```java public class Time { int seconds; int minutes; int hours; public Time(int hours, int minutes, int seconds) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; } public static void main(String[] args) { Time start = new Time(12, 34, 55), stop = new Time(8, 12, 15), diff; diff = difference(start, stop); System.out.printf("TIME DIFFERENCE: %d:%d:%d - ", start.hours, start.minutes, start.seconds); System.out.printf("%d:%d:%d ", stop.hours, stop.minutes, stop.seconds); System.out.printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds); } public static Time difference(Time start, Time stop) { Time diff = new Time(0, 0, 0); if(stop.seconds > start.seconds){ --start.minutes; start.seconds += 60; } diff.seconds = start.seconds - stop.seconds; if(stop.minutes > start.minutes){ --start.hours; start.minutes += 60; } diff.minutes = start.minutes - stop.minutes; diff.hours = start.hours - stop.hours; return(diff); } } ``` 运行该程序时,输出为: ```java TIME DIFFERENCE: 12:34:55 - 8:12:15 = 4:22:40 ``` 在上述程序中,我们创建了一个名为`Time`的类,该类具有三个成员变量:`hours`,`minutes`和`seconds`。 顾名思义,它们分别存储给定时间的`hours`,`minutes`和`seconds`。 `Time`类具有一个构造器,该构造器初始化`hours`,`minutes`和`seconds`的值。 我们还创建了一个静态函数差异,该差异将两个`Time`变量作为参数,找到该差异并将其作为`Time`类返回。