我想知道为什么我不能得到正确的时间相加结果,例如:从 2:50:20 + 0:20:40 得到 3:11:0,但是我只得到了类似 3:10 的结果: 0。所以,下面是我的工作;
//variable
int hour, min, sec;
int hour1, min1, sec1;
int total, total1, total2;
int total11,total12, total21, total22;
//input1
Scanner input = new Scanner(System.in);
System.out.print("Input hours\t: ");
hour = input.nextInt();
System.out.print("Input minutes\t: ");
min = input.nextInt();
System.out.print("Input seconds\t: ");
sec = input.nextInt();
//output1
System.out.println("Time 1 is " + hour + ":" + min + ":" + sec);
//input2
System.out.print("Input additional hours\t: ");
hour1 = input.nextInt();
System.out.print("Input additional minute\t: ");
min1 = input.nextInt();
System.out.print("Input additional seconds\t: ");
sec1 = input.nextInt();
//output2
System.out.println("Time 2 is " + jam1 + ":" + menit1 + ":" + detik1);
//process
total = hour + hour1;
total1 = min + min1;
total11 = total1/60;
total12 = total11%60;
total2 = sec + sec1;
total21 = total2/60;
total22 = total2%60;
if (total1 > 60) {
total1 = (min + min1) - 60;
total = (hour + hour1) + total11;
total2 = (sec + sec1)-60;
}
if (total2 > 60) {
total2 = (sec + sec1) - 60;
total1 = (min + min1) + total22;
}
//finaloutput
System.out.println("Your total time is " + total + ":" + total1 + ":" + total2);
*抱歉语法问题:)我真的很感谢你的回答:)
最佳答案
我发现执行这些操作的最佳方法是将两个时间都转换为秒(因此将 3:11:00 转换为午夜过后的 11460 秒),添加/减去它们,然后转换回 hh:mm: SS。大致:
int time1 = (hours1 * 60 + min1) * 60 + sec1;
int time2 = (hours2 * 60 + min2) * 60 + sec2;
int total = time1 + time2;
short hour = total / 3600;
short minute = total / 60 % 60;
short second = total %60;
关于java - Java中如何实现时间的加法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26890203/