If I have a Period object defined like this:
Period.between(LocalDate.of(2015,8,1), LocalDate.of(2015,9,2))
how to iterate over all days starting from first day until the last one? I need a loop that has an object LocalDate referring to the current date to process it.
As Jon Skeet explained, you cannot do this with java.time.Period. It is simply not an interval. There is no anchor on the date line. But you have start and end, so this is possible:
LocalDate start = LocalDate.of(2015, 8, 1);
LocalDate end = LocalDate.of(2015, 9, 2);
Stream<LocalDate> stream =
LongStream
.range(start.toEpochDay(), end.toEpochDay() + 1) // end interpreted as inclusive
.mapToObj(LocalDate::ofEpochDay);
stream.forEach(System.out::println);
Output:
2015-08-01
2015-08-02
2015-08-03
...
2015-08-31
2015-09-01
2015-09-02
There is a new way in Java 9. You can obtain Stream<LocalDate> of days between start and end.
start
.datesUntil(end)
.forEach(it -> out.print(“ > “ + it));
--
> 2017–04–14 > 2017–04–15 > 2017–04–16 > 2017–04–17 > 2017–04–18 > 2017–04–19
You can read more here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With