4

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.

Mohamed Taher Alrefaie
  • 15,698
  • 9
  • 48
  • 66
  • And to iterate given the two dates, see http://stackoverflow.com/questions/4534924/how-to-iterate-through-range-of-dates-in-java – Daniel Martin Feb 29 '16 at 11:58

4 Answers4

6

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
Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
  • Is this going to increment over every long value until it gets a new day? – Mohamed Taher Alrefaie Feb 29 '16 at 15:43
  • @M-T-A Over every long value? Yes, but only between start and end, not the whole long-range ;-) Basically this is the algorithm which is planned for new stream support for `LocalDate` in Java-9 via new proposed method `datesUntil(end)`, see also https://bugs.openjdk.java.net/browse/JDK-8146218. – Meno Hochschild Feb 29 '16 at 16:31
4

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.

Grzegorz Gajos
  • 2,253
  • 19
  • 26
2

You can't - because a Period doesn't know its start/end dates... it only knows how long it is in terms of years, months, days etc. In that respect, it's a sort of calendar-centric version of Duration.

If you want to create your own, it would be easy to do, of course - but I don't believe there's anything out of the box in either java.time (or Joda Time, as it happens) to do this.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

Even though Jon Skeet's answer is the right answer, an easy workaround would be

LocalDate currentStart=LocalDate.from(start);
LocalDate currentEnd=LocalDate.from(end.plusDays(1));//end is inclusive
do{
    // do what you want with currentStart
    //....
    currentStart=currentStart.plusDays(1);
}while (!currentStart.equals(currentEnd));
Mohamed Taher Alrefaie
  • 15,698
  • 9
  • 48
  • 66