计算两个日期之间的有效工作日

场景:工作中遇到,要计算两个日期中间的工作日的问题,此处比较简单,只计算周一到周五认为是有效工作日

//计算某个日期往后增加n个工作日的日期
public static Date getDate(Date currentDate, int days){
    Calendar calendar= Calendar.getInstance();
    calendar.setTime(currentDate);
    int i=0;
    while(i<days){
        calendar.add(Calendar.DATE,-1);//整数往后推日期,负数往前推日期
        i++;
        if(calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY ||
                calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
            i--;
        }
    }
    SimpleDateFormat dateformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    System.out.println(dateformat.format(calendar.getTime()));
    return calendar.getTime();
}
//计算两个日期之间的有效工作日
public int getDutyDays(String strStartDate,String strEndDate) {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date startDate=null;
    Date endDate = null;

    try {
        startDate=df.parse(strStartDate);
        endDate = df.parse(strEndDate);
    } catch (ParseException e) {
        System.out.println("非法的日期格式,无法进行转换");
        e.printStackTrace();
    }
    int result = 0;
    while (startDate.compareTo(endDate) <= 0) {
        if (startDate.getDay() != 6 && startDate.getDay() != 0)
            result++;
        startDate.setDate(startDate.getDate() + 1);
    }

    return result;
}

注意:我的需求比较简单,周一到周五视为有效工作日,经常的需求是还要排除法定的假日,这样的话,我们只需要将法定假日存储到自己的集合或者数据库中,在上面的基础上再排除这些特殊日期即可。

 
原创文章 84 获赞 46 访问量 21万+

猜你喜欢

转载自blog.csdn.net/yyj108317/article/details/105578995
今日推荐