diferencia sumando LocalTimes: Java

YetAnotherUser:

Tengo varias horas de trabajo en LocalTime y quiero comprobar si el tiempo supera las 24 horas. El tiempo está en formato de 24 horas.

Por ejemplo:

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

En el ejemplo anterior, supera las 24h, ya que comienza a las 2:00 y va hasta 03,00. Sólo se le permite ir hasta las 02:00.

He implementado un bucle y trató de calcular la diferencia de tiempo y resumir, por ejemplo:

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

En total sería 25h, por lo que es más grande que 24 h. Sin embargo, mi problema es que no puedo calcular la diferencia de tiempo entre 23:00-3:00 porque LocalTime sólo llega hasta las 23:59:59. Por lo tanto, actualmente no puedo calcular duraciones más allá de un período de 24 horas.

Así, utilizando ChronoUnit no funcionará:

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

No estoy seguro de qué tipo de enfoque que debe utilizar para resolver este problema

deHaar:

Si está utilizando LocalTime, entonces usted tiene que utilizar LocalTime.MINy LocalTime.MAXde un cálculo intermedio de los minutos entre los intervalos de tiempo críticos. Puede hacerlo como hecho en este método:

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;
    }
}

y se puede utilizar que en un mainmétodo como este:

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");
}

que produce la salida

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

Supongo que te gusta

Origin http://43.154.161.224:23101/article/api/json?id=364619&siteId=1
Recomendado
Clasificación