Joda time - all mondays between two dates
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);
}
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)
This code takes to string dates and gives the number of sundays and also all the sunday's dates
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class FindAllSundays {
public static int getNumberofSundays(String d1, String d2) throws Exception { // object
// in
// Date
// form
Date date1 = getDate(d1);
Date date2 = getDate(d2);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
Calendar c2 = Calendar.getInstance();
c2.setTime(date2);
int sundays = 0;
while (c2.after(c1)) {
// System.out.println(" came here ");
//checks to see if the day1 ....so on next days are sundays if sunday goes inside to increment the counter
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
System.out.println(c1.getTime().toString() + " is a sunday ");
sundays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("number of sundays between 2 dates is " + sundays);
return sundays;
}
// converts string to date
public static Date getDate(String s) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return date;
}
public static void main(String[] arg) throws Exception {
System.out.println(" " + getNumberofSundays("2005-10-07", "2006-10-01"));
}
}