需求:
需要在后端实现 计算当前日期与数据库内保存的日期数据之间相隔的工作日数目
实现
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;}
}