Starting at midnight, I want to iterate over LocalTime
s in steps of a certain period length to the end of the day.
Eg. if the period is 8hr10Minutes I would like times: 0:00, 8:10, 16:20 (not 24:30 as this is the next day)
I have the following working code for periods smaller than one day. Is there a better (esp. more readable) logic?
Duration period = ...;
for(LocalTime t = LocalTime.MIDNIGHT, p = LocalTime.MIDNIGHT;
t.isAfter(p) || t.equals(p) ; p = t, t = t.plus(period)){
// do something with t
}
Also, the above fails for periods equal to multiples of one day (infinite loop) or, if greater than one day, returns the number as if the period was cast to be shorter than one day, (eg. 24hr10min behaves the same as 10Minutes), so if that can be fixed at the same time (without explicit if
s) I'll take it as well.
I think the answer of JodaStephen is correct and not very difficult to implement. It is a complete solution also fixing any edge case.
It uses a timeIterator
to increment time for each iteration.
LocalDate date = LocalDate.of(2014, 1, 1); // arbitrary date
LocalDateTime timeIterator = LocalDateTime.of(date, LocalTime.MIDNIGHT);
do {
System.out.println(timeIterator.toLocalTime());
timeIterator = timeIterator.plus(Duration.ofHours(8).plusMinutes(10));
} while (date.equals(timeIterator.toLocalDate()));
Output:
00:00
08:10
16:20
A solution without using an arbitrary date to model the end condition would require to have the feature of counting day overflows if rolling a LocalTime
. But this feature is not offered by JSR-310 (java.time-package) and is also not really shorter in coding your special case.
The only thing which users can complain about here is the lack of built-in stream and time interval support including recurrence which might enable a shorter solution without looping.