問題描述
我需要計算兩個日期之間的工作日.例如:我們在 7 月 4 日放假(在美國).所以如果我的日期是日期 1 = 07/03/2012日期 2 = 07/06/2012
i need to calculate the business days between two dates. ex : we have holiday(in USA) on july4th. so if my dates are date1 = 07/03/2012 date2 = 07/06/2012
由于 7 月 4 日是假期,因此這些日期應該是 1 個工作日.
no of business days b/w these dates should be 1 since july4th is holiday.
我有一個下面的方法來計算工作日,它只計算周末而不是假期.還有什么方法可以計算假期....請幫助我.
i have a below method to calclulate the business days which will only counts week ends but not holidays. is there any way to calculate holidays also....please help me on this.
public static int getWorkingDaysBetweenTwoDates(Date startDate, Date endDate) {
Calendar startCal;
Calendar endCal;
startCal = Calendar.getInstance();
startCal.setTime(startDate);
endCal = Calendar.getInstance();
endCal.setTime(endDate);
int workDays = 0;
//Return 0 if start and end are the same
if (startCal.getTimeInMillis() == endCal.getTimeInMillis()) {
return 0;
}
if (startCal.getTimeInMillis() > endCal.getTimeInMillis()) {
startCal.setTime(endDate);
endCal.setTime(startDate);
}
do {
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY
&& startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
++workDays;
}
} while (startCal.getTimeInMillis() < endCal.getTimeInMillis());
return workDays;
}
推薦答案
假設您有一個包含所有假期的列表,正如您所提到的.
Let's pretend you have a list containing all the holidays, as you mentioned.
ArrayList<Integer> holidays = ...
只需在 do-while
中為 if
條件添加一個條件:
Just add a condition to your if
condition in your do-while
:
do {
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY
&& startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY
&& !holidays.contains((Integer) startCal.get(Calendar.DAY_OF_YEAR))) {
++workDays;
}
} while (startCal.getTimeInMillis() < endCal.getTimeInMillis());
為簡單起見,我假設 holiday
包含格式與 Calendar.DAY_OF_YEAR
相同的日期.
For simplicity's sake, I've assumed holiday
contains dates in the format identical to Calendar.DAY_OF_YEAR
.
這篇關于計算包括節(jié)假日在內的工作日的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!