如何在Java中计算任何月份的工作日数?我的输入将是int月份。 例如,要获取9月的工作日数,我的输入应为9。 我确实有开始或结束日期。周末是星期六和星期日。请帮忙。
答案 0 :(得分:0)
此方法可能不是最佳方法,但至少可以避免任何循环。我试图从字面上解决它,所以这是一般的想法,希望它适合您:
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
}