欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-18 08:02:04
...
    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;
    }

相关标签: java java