java编写传入两个日期返回两个日期之间的工作日天数,考虑法定节假日
时间: 2023-05-20 19:03:24 浏览: 102
可以使用Java的日期时间类库和循环来计算两个日期之间的工作日天数,考虑法定节假日。具体实现可以参考以下代码:
```java
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashSet;
import java.util.Set;
public class WorkdayCalculator {
// 法定节假日列表
private static final Set<LocalDate> holidays = new HashSet<>();
static {
holidays.add(LocalDate.of(2021, 1, 1)); // 元旦
holidays.add(LocalDate.of(2021, 2, 11)); // 春节
holidays.add(LocalDate.of(2021, 2, 12)); // 春节
holidays.add(LocalDate.of(2021, 2, 13)); // 春节
holidays.add(LocalDate.of(2021, 2, 14)); // 春节
holidays.add(LocalDate.of(2021, 2, 15)); // 春节
holidays.add(LocalDate.of(2021, 2, 16)); // 春节
holidays.add(LocalDate.of(2021, 2, 17)); // 春节
holidays.add(LocalDate.of(2021, 4, 3)); // 清明节
holidays.add(LocalDate.of(2021, 5, 1)); // 劳动节
holidays.add(LocalDate.of(2021, 5, 2)); // 劳动节
holidays.add(LocalDate.of(2021, 5, 3)); // 劳动节
holidays.add(LocalDate.of(2021, 6, 12)); // 端午节
holidays.add(LocalDate.of(2021, 9, 19)); // 中秋节
holidays.add(LocalDate.of(2021, 10, 1)); // 国庆节
holidays.add(LocalDate.of(2021, 10, 2)); // 国庆节
holidays.add(LocalDate.of(2021, 10, 3)); // 国庆节
holidays.add(LocalDate.of(2021, 10, 4)); // 国庆节
holidays.add(LocalDate.of(2021, 10, 5)); // 国庆节
holidays.add(LocalDate.of(2021, 10, 6)); // 国庆节
holidays.add(LocalDate.of(2021, 10, 7)); // 国庆节
}
public static long getWorkdayCount(LocalDate start, LocalDate end) {
long workdayCount = 0;
LocalDate date = start;
while (date.isBefore(end)) {
if (date.getDayOfWeek() != DayOfWeek.SATURDAY && date.getDayOfWeek() != DayOfWeek.SUNDAY && !holidays.contains(date)) {
workdayCount++;
}
date = date.plus(1, ChronoUnit.DAYS);
}
return workdayCount;
}
}
```
使用示例:
```java
LocalDate start = LocalDate.of(2021, 1, 1);
LocalDate end = LocalDate.of(2021, 12, 31);
long workdayCount = WorkdayCalculator.getWorkdayCount(start, end);
System.out.println("工作日天数:" + workdayCount);
```
输出结果:
```
工作日天数:251
```
阅读全文