If you are using LocalTime, then you have to use LocalTime.MIN and LocalTime.MAX for an intermediate calculation of the minutes between critical time slots. You can do it like done in this method:
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;
}
}
and you can use that in a main method like this:
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");
}
which produces the output
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