java:求和 LocalTimes 差异

java: summing LocalTimes difference

我在 LocalTime 中有多个工作时间,我想检查时间是否超过 24 小时。 时间为 24 小时制。

例如:

  1. 02:00 - 08:00
  2. 10:00 - 12:00
  3. 23:00 - 03:00

在上面的例子中,它超过了 24 小时,因为它从 02:00 开始,一直持续到 03.00。 只允许到 02:00.

我实现了一个循环,尝试计算时间差并求和,例如:

  1. 02:00 - 08:00 --> 6 小时
  2. 08:00 - 10:00 --> 2 小时
  3. 10:00 - 12:00 --> 2 小时
  4. 12:00 - 23:00 --> 11h
  5. 23:00 - 03:00 --> 4 小时

一共是25小时,比24小时大。 但是我的问题是我无法计算 23:00 - 03:00 之间的时差,因为 LocalTime 只持续到 23:59:59。所以我目前无法计算超过 24 小时的持续时间。

所以使用 ChronoUnit 将不起作用:

ChronoUnit.HOURS.between(23:00, 03:00);

我不确定我应该用什么样的方法来解决这个问题

ChronoUnit.HOURS.between(LocalTime.of(23, 0), LocalTime.of(03,0)

这会给你-20,如果结果小于零,你可以做一些数学运算,意味着 24 -20 = 4,所以使用 ChronoUnit 可以工作,但最好使用 LocalDateTime

如果您使用 LocalTime,则必须使用 LocalTime.MINLocalTime.MAX 对关键时间段之间的分钟数进行中间计算。你可以像在这个方法中那样做:

public static long getHoursBetween(LocalTime from, LocalTime to) {
    // if start time is before end time...
    if (from.isBefore(to)) {
        // ... just return the hours between them,
        return Duration.between(from, to).toHours();
    } else {
        /*
         * otherwise take the MINUTES between the start time and max LocalTime
         * AND ADD 1 MINUTE due to LocalTime.MAX being 23:59:59
         */
        return ((Duration.between(from, LocalTime.MAX).toMinutes()) + 1
                /*
                 * and add the the MINUTES between LocalTime.MIN (0:00:00)
                 * and the end time
                 */
                + Duration.between(LocalTime.MIN, to).toMinutes())
                // and finally divide them by sixty to get the hours value
                / 60;
    }
}

您可以像这样在 main 方法中使用它:

public static void main(String[] args) {
    // provide a map with your example data that should sum up to 24 hours
    Map<LocalTime, LocalTime> fromToTimes = new HashMap<>();
    fromToTimes.put(LocalTime.of(2, 0), LocalTime.of(8, 0));
    fromToTimes.put(LocalTime.of(8, 0), LocalTime.of(10, 0));
    fromToTimes.put(LocalTime.of(10, 0), LocalTime.of(12, 0));
    fromToTimes.put(LocalTime.of(12, 0), LocalTime.of(23, 0));
    fromToTimes.put(LocalTime.of(23, 0), LocalTime.of(3, 0));

    // print the hours for each time slot
    fromToTimes.forEach((k, v) -> System.out.println("from " + k + " to " + v 
            + "\t==>\t" + getHoursBetween(k, v) + " hours"));

    // sum up all the hours between key and value of the map of time slots
    long totalHours = fromToTimes.entrySet().stream()
            .collect(Collectors.summingLong(e -> getHoursBetween(e.getKey(), e.getValue())));

    System.out.println("\ttotal\t\t==>\t" + totalHours + " hours");
}

产生输出

from 08:00 to 10:00 ==> 2 hours
from 23:00 to 03:00 ==> 4 hours
from 10:00 to 12:00 ==> 2 hours
from 02:00 to 08:00 ==> 6 hours
from 12:00 to 23:00 ==> 11 hours
        total       ==> 25 hours