在此程序中,您将学习计算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); } }
运行该程序时,输出为:
TIME DIFFERENCE: 12:34:55 - 8:12:15 = 4:22:40
在上面的程序,我们已经创建了一个名为Time类有三个成员变量hours,minutes和seconds。正如名字所暗示的,它们分别给定的时间存储hours,minutes和seconds。
Time类具有一个构造函数,用于初始化hours,minutes和seconds。
我们还创建了一个静态函数difference,它接受两个时间变量作为参数,查找差异并将其作为Time类返回