如何避免时差为负时间?

2024-01-16

我正在开发一个使用 Java8 Time 的应用程序。我面临一个问题。

假设时间 A 是 08:00,时间 B 是 17:00,那么这两个时间之间的差异将是 9 小时,在我的情况下这是正确的,但如果时间 A 是 18:00,时间 B 是 02:00应该是 8h,但在我的例子中,我的程序返回 -16。请有人指导我如何解决这个问题。

My code:

@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班级?它适用于像您这样的情况。

    Duration calculatedTime = Duration.between(startTime, endTime);
    if (calculatedTime.isNegative()) {
        calculatedTime = calculatedTime.plusDays(1);
    }

    System.out.println(calculatedTime);

这会以 ISO 8601 格式打印持续时间:

PT8H

要在 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 中格式化(未测试):

    String formattedTime = String.format("%d:%02d", 
                                         calculatedTime.toHoursPart(),
                                         calculatedTime.toMinutesPart());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何避免时差为负时间? 的相关文章

随机推荐