Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate on all weeks between start, finish date

Tags:

java

datetime

I have two Date objects, start and finish. I want to iterate them on a weekly basis, i.e. if there are exactly 4 weeks in between (calendar weeks, not just 7 days after each other), I want 4 iterations and in each iteration I want to get the actual start and end Dates.

I'm currently hacking up an Iterable for the purpose, but I'm thinking if it can be achieved easily with for example Joda Time or a smart custom method. Thanks in advance!

EDIT: I must repeat that I need weeks as in calendar, not seven days after each other. If my start date is on a random day in the week (for example friday), my first iteration should contain [friday,sunday] not [friday,friday+7 days]. Solution posted as answer.

like image 803
gyorgyabraham Avatar asked Dec 18 '25 20:12

gyorgyabraham


1 Answers

In Java 9 there is a nice LocalDate.datesUntil method. There is also an easy way to adjust time within a week boundaries using TemporalAdjusters.

    int numOfWeeks = 4;

    // First iteration with alignment
    LocalDate start = LocalDate.now();
    LocalDate endOfTheFirstWeek = start.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
    out.println(String.format("[%s,%s]", start, endOfTheFirstWeek));

    // Remaining iterations
    endOfTheFirstWeek
            .datesUntil(endOfTheFirstWeek.plusWeeks(numOfWeeks - 1), Period.ofWeeks(1))
            .forEach(it -> {
                LocalDate from = it.plusDays(1);
                LocalDate to = from.plusWeeks(1);
                out.println(String.format("[%s,%s]", from, to));
            });
like image 129
Grzegorz Gajos Avatar answered Dec 21 '25 11:12

Grzegorz Gajos