Java实现计算当前日期往前推n个工作日代码实现

需求:取当前日期,并往前推n个工作日,返回计算出来的日期(工作日仅去掉周六日,并未考虑春节之类的假期)

public class Test {

    public static void main(String[] args) {
        Date now = DateUtil.parse("2023-7-23 00:00:00", DatePattern.NORM_DATETIME_FORMAT);
        System.out.println("当前时间:" + DateUtil.formatDateTime(now));
        for (int i = 0; i <= 10; i++) {
            Date workDate = getWorkDate(now, i);
            System.out.println("减去" + i + "天后时间:" + DateUtil.formatDateTime(workDate));
        }
    }

    public static Date getWorkDate(Date date, int n) {
        //实际要扣减的天数(计算出加上周末的时间)
        //算出有几周,然后按照7天进行放大
        int num = n / 5 * 7;
        //根据当前星期几,确定要微调的天数
        Calendar instance = Calendar.getInstance();
        instance.setTime(date);
        int dayOfWeek = instance.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 1) {
            //周日,额外减2天
            num += n % 5 + 2;
        } else if (dayOfWeek == 7) {
            //周六,额外减1天
            num += n % 5 + 1;
        } else {
            //工作日
            num += n % 5;
        }
        instance.add(Calendar.DATE, -num);
        return instance.getTime();
    }

}

觉得内容还不错?打赏个钢镚鼓励鼓励!!👍