views:

75

answers:

1

Hi,

I need to find all the weekend dates for a given month and year, eg: 01(month), 2010(year) . the output should be :- 2,3,9,10,16,17,23,24,30,31. all weekend dates. please any idea.

usman

+3  A: 

Here is a rough version with comments describing the steps:

// create a Calendar for the 1st of the required month
int year = 2010;
int month = Calendar.JANUARY;
Calendar cal = new GregorianCalendar(year, month, 1);
do {
    // get the day of the week for the current day
    int day = cal.get(Calendar.DAY_OF_WEEK);
    // check if it is a Saturday or Sunday
    if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) {
        // print the day - but you could add them to a list or whatever
        System.out.println(cal.get(Calendar.DAY_OF_MONTH));
    }
    // advance to the next day
    cal.add(Calendar.DAY_OF_YEAR, 1);
}  while (cal.get(Calendar.MONTH) == month);
// stop when we reach the start of the next month
mikej
sample is not working properly it gives output :2,3,9,10,16,17,23,24,30, but for jan 2010 the week end list are2,3,9,10,16,17,23,24,30,31 . please tell me where is the pro
usman
There was a bug in the `while` condition where the last day of the month was being missed. I have fixed it now.
mikej
Thank you very much mikej
usman