Если вы используете LocalTime
, то вы должны использовать LocalTime.MIN
и LocalTime.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