gpt4 book ai didi

Java 减去 HH :MM:SS 中的 2 持续时间

转载 作者:行者123 更新时间:2023-11-29 04:53:23 26 4
gpt4 key购买 nike

我在 java 中有 2 个字符串 (HH:MM:SS) 请注意这是不是时间,而是持续时间,我使用结束时间 - 开始时间来获取这些值:

案例一:

duration1 = "12:04:45";

duration2 = "13:04:45";

预期结果:duration1 - duration 2 = "-1:00:00"(注意有负数)

案例2:

duration1 = "15:13:32";

duration2 = "12:04:45";

预期结果:duration1 - duration 2 = "3:08:47"

我该怎么做?我对 Case1 的尝试(代码修改自 Java add dates of format dd:HH:mm:ss ):

SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");    

String s1 = "12:04:45";
String s2 = "13:04:45";

Date d1 = format.parse(s1);
Date d2 = format.parse(s2);

int sec = d1.getSeconds() - d2.getSeconds();
int min = d1.getMinutes() - d2.getMinutes();
int hr = d1.getHours() - d2.getHours();

Time sum = new Time(hr, min, sec);
System.out.println(sum); // Output: 23:00:00 which is wrong

最佳答案

如果您的经期超过 24 小时,则像某些人建议的那样使用 LocalTime 或日期计算是行不通的,因为这不适合一天。

如果您没有 Java 8,可以使用 JodaTime。我刚刚检查过这段代码是否也适用于 JodaTime 1.6.2,这是仍然适用于 JDK 1.4.2 的最后一个版本。

PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroAlways().minimumPrintedDigits(2)
.appendHours().appendSuffix(":").appendMinutes().appendSuffix(":").appendSeconds()
.toFormatter();
Period period1 = formatter.parsePeriod("12:04:45");
Period period2 = formatter.parsePeriod("13:04:45");
Period difference1 = period1.minus(period2).normalizedStandard();
System.out.println(formatter.print(difference1));

Period period3 = formatter.parsePeriod("15:13:32");
Period period4 = formatter.parsePeriod("12:04:45");
Period difference2 = period3.minus(period4).normalizedStandard();
System.out.println(formatter.print(difference2));

输出:

-01:00:00
03:08:47

乔达时间:

关于Java 减去 HH :MM:SS 中的 2 持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34611836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com