java实现时间区间内相差天数不含周末

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Test {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date s = sdf.parse("2022-01-01");
            Date e=sdf.parse("2022-01-10");
            int d=getWorkDays(s,e);
            System.out.println("工作日"+d);
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    public static int getWorkDays(Date startTime, Date endTime) {
        int workDays = 0;

        // 日期格式化
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 起始日期
            Date begin = simpleDateFormat.parse(simpleDateFormat.format(startTime));
            // 结束日期
            Date end = simpleDateFormat.parse(simpleDateFormat.format(endTime));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(begin);
            while (begin.getTime() <= end.getTime()) {
                //获取当前日期是周几
                int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                if (week != 0 && week != 6) {//0为周日,6为周六
                    workDays += 1;
                }
                begin = calendar.getTime();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return workDays;
    }
}

你可能感兴趣的:(JAVASE,算法,idea,java)