Java 9. Stream of days between dates.

In Java 9 we have a new method in LocalDate class. I am talking here about datesUntil. How it works? Let’s say we have two variables with local dates:

LocalDate start =;
LocalDate end = start.plusDays(6);

Now, let’s say we want to display each day between those two dates. Are you thinking about some simple loop now? Adding a day on each iteration and displaying the current day? Good, it is going to work but here’s alternative, straight from the Java 9.

.forEach(it -> out.print(“ > “ + it));
// > 2017–04–14 > 2017–04–15 > 2017–04–16 > 2017–04–17 > 2017–04–18 > 2017–04–19

What datesUntil actually do? According to the declaration it returns a stream of LocalDate’s. Nice, we can perform all the lambda goodies. Let’s have a look on the Javadoc.

Returns a sequential ordered stream of dates. The returned stream starts from this date (inclusive) and goes to end (exclusive) by an incremental step of 1 day. This method is equivalent to datesUntil(endExclusive, Period.ofDays(1))

Hey, so there is another method that accepts second argument. How it works? What if we would like to iterate monthly?:

.datesUntil(start.plusMonths(4), Period.ofMonths(1))
.forEach(it -> out.print(" > " + it));
// > 2017-04-14 > 2017-05-14 > 2017-06-14 > 2017-07-14

Can we use LocalDateTime and iterate hourly? No, we can’t. Seems like there is no equivalent when operating with time precision. Period was introduced with Java 8 already and it’s dedicated to days/months/years. Unfortunately, no notion of the time related goodies there.