java 获取n天之后的工作日,不考虑节假日
程序员文章站
2022-05-17 20:34:37
...
看过网上的相关代码,思路大多数是迭代日期以排除周末,效率不是很高,自己写了一个。仅供参阅
/**
* 获取n天之后的工作日
* @param today
* @param afterDays
* @return
*/
public static Date getAfterWorkDay(Date today, Integer afterDays){
if (today == null) {
throw new BussinessException("当前日期不能为空");
}
if (afterDays == null) {
throw new BussinessException("周期不能为空");
}
Integer workAfterDays = afterDays;
/**
* 计算经过几个周末
*/
Integer cycle = 7;
Integer i = afterDays / cycle;
workAfterDays += i * 2;
Calendar c = Calendar.getInstance();
c.setTime(today);
c.add(Calendar.DAY_OF_MONTH, workAfterDays);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
if(c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
c.add(Calendar.DAY_OF_MONTH, 2);
} else if(c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
c.add(Calendar.DAY_OF_MONTH, 1);
}
return c.getTime();
}
下一篇: 【Java】比较两个日期相差的天数