java计算工作日,不包含节假日 代码实现
时间: 2024-02-02 18:02:37 浏览: 90
java计算工作时间除去节假日以及双休日
5星 · 资源好评率100%
以下是Java中计算工作日的代码实现,不包含节假日:
```java
import java.time.DayOfWeek;
import java.time.LocalDate;
public class WorkingDaysCalculator {
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) {
workingDays++;
}
currentDate = currentDate.plusDays(1);
}
return workingDays;
}
}
```
在以上代码中,我们使用了Java 8的日期时间API,即`java.time`包。`LocalDate`类表示一个日期,`DayOfWeek`枚举表示星期几。`countWorkingDays`方法使用一个循环来遍历给定日期范围内的每一天,并检查是否是星期六或星期日。如果是工作日,计数器`workingDays`就会加一。最后,该方法返回计数器的值,即工作日的总数。
阅读全文