如何避免时间差之间的负值时间? [英] How to avoid negative time between time difference?
问题描述
我正在开发一个使用Java8 Time的应用程序.我面临一个问题.
I'm developing an app in which I'm using Java8 Time. I'm facing an issue.
让我们说时间A为08:00,时间B为17:00,所以这两个时间之间的时差为9h,在我的情况下是正确的,但是如果时间A为18:00而时间B为02 :00应该是8h,但就我而言,我的程序返回-16.请有人指导我如何解决这个问题.
Let's say Time A is 08:00 and Time B is 17:00, so the difference of between these two times will be 9h which in my case is correct, but if Time A is 18:00 and Time B is 02:00 it should be 8h, but in my case my program is returning -16. Kindly someone guide me how to solve this.
我的代码:
@Test
public void testTime()
{
DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");
String s = "18:00";
String e = "02:00";
// Parse datetime string to java.time.LocalDateTime instance
LocalTime startTime = LocalTime.parse(s, format);
LocalTime endTime = LocalTime.parse(e, format);
String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
+ ChronoUnit.MINUTES.between(startTime, endTime)%60;
System.out.println(calculatedTime);
}
推荐答案
为什么不使用Duration
类?它适用于像您这样的情况.
Why not use the Duration
class? It’s meant for situations like yours.
Duration calculatedTime = Duration.between(startTime, endTime);
if (calculatedTime.isNegative()) {
calculatedTime = calculatedTime.plusDays(1);
}
System.out.println(calculatedTime);
这将以ISO 8601格式打印持续时间:
This prints the duration in ISO 8601 format:
PT8H
要在Java 8中对其进行格式化,请执行以下操作:
To format it in Java 8:
long hours = calculatedTime.toHours();
calculatedTime = calculatedTime.minusHours(hours);
String formattedTime = String.format(Locale.getDefault(), "%d:%02d",
hours, calculatedTime.toMinutes());
System.out.println(formattedTime);
此打印
8:00
要使用Java 9格式化(未测试):
To format in Java 9 (not tested):
String formattedTime = String.format("%d:%02d",
calculatedTime.toHoursPart(),
calculatedTime.toMinutesPart());
这篇关于如何避免时间差之间的负值时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!