-10

How to calculate number of working days for any month in java? My input would be month in int. For example - to get the number of working days in September, my input would be 9. I done have the start or end dates. Weekends are Saturday and Sunday. Please help.

user3649712
  • 13
  • 1
  • 5

1 Answers1

0

This approach could be not the most optimal, but at least avoids any loops. I tried to solve it literally, so here's the general idea, hope it fits you:

static int countHolidays(int month){
    //assuming month is 1-12
    Calendar firstDayCal = Calendar.getInstance();
    Calendar lastDayCal = Calendar.getInstance();
    firstDayCal.set(Calendar.MONTH, month-1);//here we should put 0-11;
    lastDayCal.set(Calendar.MONTH, month-1);
    int firstDay = firstDayCal.getActualMinimum(Calendar.DAY_OF_MONTH);
    int lastDay = firstDayCal.getActualMaximum(Calendar.DAY_OF_MONTH);
    firstDayCal.set(Calendar.DAY_OF_MONTH, firstDay);
    lastDayCal.set(Calendar.DAY_OF_MONTH, lastDay);
    //any month have no less than 28 days, so 4 full weeks - so 8 weekends.
    int total = 8;
    switch (lastDay) {
        case 29:
            //leap-year february can have one extra holiday if it starts on sunday or ends on saturday
            if ((firstDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) || (lastDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)){
                total++;
            }   break;
        case 30:
            //30-day month can have one extra holiday if it starts on sunday or ends on saturday...
            if ((firstDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) || (lastDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)){
                total++;
            //...or two extra holiday if it starts on saturday or ends on sunday
            } else if ((firstDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) || (lastDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)){
                total = total + 2;
            }   break;
        case 31:
            //31-day month can have one extra holiday if it starts on sunday or ends on saturday...
            if ((firstDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) || (lastDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)){
                total++;
            //...or two extra holiday if it starts on (friday or saturday) or ends on (sunday or monday)
            } else if (((firstDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) || (firstDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY)) ||
                    ((lastDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) || (lastDayCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY))) {
                total = total + 2;
            }   break;
        default:
            break;
    }
    return lastDay-total;//as we need workingDays, not weekends        
}