Java 计算两个日期之间相差多少工作日

    public Long getWorkTime(Date startDate, Date endDate) {
        String start = DateFormatUtils.format(startDate.getTime(), "yyyy-MM-dd");
        String end = DateFormatUtils.format(endDate.getTime(), "yyyy-MM-dd");
        /**
         * 由数据库配置表中查出
         * 特殊的工作日(星期六、日工作)
         */
        List<String> specialWorkDays = this.baseMapper.selectSpecialWorkDays(start, end);
        /**
         * 由数据库配置表中查出
         * 特殊的休息日(星期一到五休息)
         */
        List<String> specialRestDays = this.baseMapper.selectSpecialRestDays(start, end);
        
        
        return getworkTime(start, end, specialWorkDays, specialRestDays, startDate, endDate);
    }

    private Long getworkTime(String strStartDate, String strEndDate, List<String> specialWorkDays, List<String> specialRestDays, Date startDate, Date endDate) {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        Calendar cl1 = Calendar.getInstance();
        Calendar cl2 = Calendar.getInstance();

        try {
            cl1.setTime(df.parse(strStartDate));
            cl2.setTime(df.parse(strEndDate));

        } catch (ParseException e) {
            System.out.println("日期格式非法");
            e.printStackTrace();
        }

        // 休息日天数
        int count = 0;
        while (cl1.compareTo(cl2) <= 0) {
            //如果是周六或者周日则休息日+1
            if (cl1.get(Calendar.DAY_OF_WEEK) == 7 || cl1.get(Calendar.DAY_OF_WEEK) == 1) {
                count++;
                //如果是周六或者周日,但是该日属于需要工作的日子则 -1
                if (specialWorkDays.contains(DateFormatUtils.format(cl1.getTime(), "yyyy-MM-dd"))) {
                    count--;
                }
            }
            //如果不是周六或者周日,但是该日属于国家法定节假日或者特殊放假日则+1
            if (specialRestDays.contains(DateFormatUtils.format(cl1.getTime(), "yyyy-MM-dd"))) {
                count++;
            }
            cl1.add(Calendar.DAY_OF_MONTH, 1);
        }

        Long time= endDate.getTime() - startDate.getTime();

        time = time - (count * 1000 * 60 * 60 * 24L);

        return time;
    }

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值