Java 计算两个日期之间的工作日(排除法定节假日和周末,包含调休工作日)
时间: 2024-01-23 12:04:26 浏览: 276
java计算整年工作日(包含特殊的工作日)排除法定节假日和周末能运行
以下是 Java 计算两个日期之间的工作日(排除法定节假日和周末,包含调休工作日)的示例代码:
```java
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
public class WorkingDaysCalculator {
public static long getWorkingDays(LocalDate startDate, LocalDate endDate, List<LocalDate> holidays, List<LocalDate> workingDays) {
long workingDaysCount = 0;
LocalDate date = startDate;
while (date.isBefore(endDate)) {
if (date.getDayOfWeek() != DayOfWeek.SATURDAY && date.getDayOfWeek() != DayOfWeek.SUNDAY && !holidays.contains(date)) {
workingDaysCount++;
} else if (workingDays.contains(date)) {
workingDaysCount++;
}
date = date.plus(1, ChronoUnit.DAYS);
}
return workingDaysCount;
}
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2021, 1, 1);
LocalDate endDate = LocalDate.of(2021, 1, 31);
List<LocalDate> holidays = new ArrayList<>();
holidays.add(LocalDate.of(2021, 1, 1));
holidays.add(LocalDate.of(2021, 1, 6));
holidays.add(LocalDate.of(2021, 1, 20));
List<LocalDate> workingDays = new ArrayList<>();
workingDays.add(LocalDate.of(2021, 1, 2));
workingDays.add(LocalDate.of(2021, 1, 3));
long workingDaysCount = getWorkingDays(startDate, endDate, holidays, workingDays);
System.out.println("Number of working days between " + startDate + " and " + endDate + ": " + workingDaysCount);
}
}
```
与前面的示例相比,这个示例增加了一个 `List<LocalDate> workingDays` 参数来表示调休工作日的日期。在 `getWorkingDays` 方法中,我们使用 `while` 循环遍历两个日期之间的每一天,并使用 `getDayOfWeek` 方法来判断一周中的哪一天。如果这一天不是周六或周日,且不是法定节假日,则将其计为工作日;如果这一天是调休工作日,则也计为工作日。最终,我们将工作日数作为方法的返回值,并在 `main` 方法中打印出来。
阅读全文