Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to iterate over days in a Period object

Tags:

java

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.

like image 502
Mohamed Taher Alrefaie Avatar asked Oct 30 '25 01:10

Mohamed Taher Alrefaie


2 Answers

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
like image 173
Meno Hochschild Avatar answered Oct 31 '25 14:10

Meno Hochschild


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.

like image 40
Grzegorz Gajos Avatar answered Oct 31 '25 15:10

Grzegorz Gajos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!