Philipp
Philipp

Reputation: 4799

Java 8 time: Iterate over a day's LocalTime in period steps

Starting at midnight, I want to iterate over LocalTimes 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 ifs) I'll take it as well.

Upvotes: 2

Views: 3148

Answers (2)

Meno Hochschild
Meno Hochschild

Reputation: 44071

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.

Upvotes: 5

JodaStephen
JodaStephen

Reputation: 63445

There is no built in code to support this kind of iteration.

It might be easier to use LocalDateTime that LocalTime because it would handle the end condition better (use an arbitrary date if there is no obvious date to use, and then loop until the date is the following date.)

Upvotes: 2

Related Questions