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.
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));
});
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