calculate business days including holidays(计算包括节假日在内的工作日)
问题描述
我需要计算两个日期之间的工作日.例如:我们在 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
.
这篇关于计算包括节假日在内的工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:计算包括节假日在内的工作日


基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01