java 计算工作日
时间: 2023-10-11 18:26:11 浏览: 75
Java计算工作日
以下是 Java 中计算工作日的代码实现,包含节假日:
```java
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class WorkingDaysCalculator {
// 节假日列表
private static List<LocalDate> holidayList = new ArrayList<>();
static {
// 添加节假日,这里以2021年为例
holidayList.add(LocalDate.of(2021, 1, 1)); // 元旦
holidayList.add(LocalDate.of(2021, 2, 11)); // 春节
holidayList.add(LocalDate.of(2021, 2, 12)); // 春节
holidayList.add(LocalDate.of(2021, 2, 15)); // 春节
holidayList.add(LocalDate.of(2021, 2, 16)); // 春节
holidayList.add(LocalDate.of(2021, 2, 17)); // 春节
holidayList.add(LocalDate.of(2021, 4, 5)); // 清明节
holidayList.add(LocalDate.of(2021, 5, 1)); // 劳动节
holidayList.add(LocalDate.of(2021, 5, 3)); // 劳动节
holidayList.add(LocalDate.of(2021, 5, 4)); // 劳动节
holidayList.add(LocalDate.of(2021, 6, 14)); // 端午节
holidayList.add(LocalDate.of(2021, 9, 20)); // 中秋节
holidayList.add(LocalDate.of(2021, 10, 1)); // 国庆节
holidayList.add(LocalDate.of(2021, 10, 2)); // 国庆节
holidayList.add(LocalDate.of(2021, 10, 3)); // 国庆节
holidayList.add(LocalDate.of(2021, 10, 4)); // 国庆节
holidayList.add(LocalDate.of(2021, 10, 5)); // 国庆节
holidayList.add(LocalDate.of(2021, 10, 6)); // 国庆节
holidayList.add(LocalDate.of(2021, 10, 7)); // 国庆节
}
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2021, 10, 1);
LocalDate endDate = LocalDate.of(2021, 10, 31);
int workingDays = countWorkingDays(startDate, endDate);
System.out.println("Working days between " + startDate + " and " + endDate + ": " + workingDays);
}
public static int countWorkingDays(LocalDate startDate, LocalDate endDate) {
int workingDays = 0;
LocalDate currentDate = startDate;
while (currentDate.isBefore(endDate) || currentDate.isEqual(endDate)) {
if (currentDate.getDayOfWeek() != DayOfWeek.SATURDAY && currentDate.getDayOfWeek() != DayOfWeek.SUNDAY
&& !holidayList.contains(currentDate)) {
workingDays++;
}
currentDate = currentDate.plusDays(1);
}
return workingDays;
}
}
```
在以上代码中,我们通过一个静态初始化块构建了节假日列表。然后,在`countWorkingDays`方法中,我们在每个循环迭代中检查当前日期是否是星期六、星期日或节假日。如果不是,计数器`workingDays`就会加一。最后,该方法返回计数器的值,即工作日的总数。
阅读全文