I have multiple working hours in LocalTime and I want to check if the time exceeds 24 hours. The time is in 24h format.
For example:
- 02:00 - 08:00
- 10:00 - 12:00
- 23:00 - 03:00
In the example above, it exceeds 24h since it starts at 02:00 and goes till 03.00. It is only allowed to go till 02:00.
I implemented a loop and tried to calculate the time difference and sum it, for example:
- 02:00 - 08:00 --> 6 h
- 08:00 - 10:00 --> 2 h
- 10:00 - 12:00 --> 2 h
- 12:00 - 23:00 --> 11h
- 23:00 - 03:00 --> 4 h
In total it would be 25h, so it is bigger than 24h. However my problem is that I cannot calculate the time difference between 23:00 - 03:00 because LocalTime only goes till 23:59:59. So I currently I cannot calculate durations beyond a 24 hour period.
So using ChronoUnit won't work:
ChronoUnit.HOURS.between(23:00, 03:00);
I am not sure what kind of approach I should use to solve this problem
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