Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda time - all mondays between two dates

I am using Joda time api in a Spring 3.0 project for the very first time. Now I have a start and end date and I want to get the date for all mondays between these two dates. How can I do this ?

I have no idea where to start, can someone please advise. I looked at theis post Joda Time: How to get dates of weekdays on some date interval? and it offered some sort of guidance but its still somewhat vague due to little experience with joda.

like image 610
Faiyet Avatar asked Nov 07 '11 18:11

Faiyet


2 Answers

LocalDate startDate = new LocalDate(2011, 11, 8);
LocalDate endDate = new LocalDate(2012, 5, 1);

LocalDate thisMonday = startDate.withDayOfWeek(DateTimeConstants.MONDAY);

if (startDate.isAfter(thisMonday)) {
    startDate = thisMonday.plusWeeks(1); // start on next monday
} else {
    startDate = thisMonday; // start on this monday
}

while (startDate.isBefore(endDate)) {
    System.out.println(startDate);
    startDate = startDate.plusWeeks(1);
}
like image 54
lschin Avatar answered Sep 28 '22 11:09

lschin


I recently developed Lamma which is designed to solve this exact use case:

Dates.from(2011, 11, 8).to(2011, 12, 30).byWeek().on(DayOfWeek.MONDAY).build();

and you will get a List<Date> of:

Date(2011,11,14)
Date(2011,11,21)
Date(2011,11,28)
Date(2011,12,5)
Date(2011,12,12)
Date(2011,12,19)
Date(2011,12,26)
like image 36
Max Avatar answered Sep 28 '22 12:09

Max