Java实现计算两个日期之间的工作日天数

需求:

需要在后端实现 计算当前日期与数据库内保存的日期数据之间相隔的工作日数目

实现

import java.time.DayOfWeek;
import java.time.LocalDateTime;

public class WorkdaysCalculator {
    public static void main(String[] args) {
        String givenDateTimeStr = "2022-01-01T12:34:56.789"; // 替换为你的日期时间字符串

        LocalDateTime currentDateTime = LocalDateTime.now(); // 获取当前时间
        LocalDateTime givenDateTime = LocalDateTime.parse(givenDateTimeStr);

        int workdaysCount = 0;  // 记录相隔工作日数目
        int daysCount = 0;  // 记录相隔天数总数目
		// 循环 直到当前日期在给定日期之前
        while (currentDateTime.isAfter(givenDateTime) || currentDateTime.equals(givenDateTime)) {
            if (isWorkday(currentDateTime.getDayOfWeek())) {
                workdaysCount++;
            }
            currentDateTime = currentDateTime.minusDays(1);  // 当前日期减去一天
            daysCount++;
        }

        if (workdaysCount > 90) {
            System.out.println("给定日期超过90个工作日");
        } else {
            System.out.println("给定日期不超过90个工作日");
        }

        System.out.println("总天数:" + daysCount);
        System.out.println("工作日天数:" + workdaysCount);
    }

    private static boolean isWorkday(DayOfWeek dayOfWeek) { //校验当前日期是否为工作日
        return dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY;
    }
}

你可能感兴趣的:(小工具记录,java,开发语言)