java计算两个日期的工作日
时间: 2024-10-17 11:14:15 浏览: 37
在Java中,计算两个日期之间的工作日可以使用`java.time`包下的`LocalDate`和`BusinessDayCalculator`类。以下是一个简单的示例:
```java
import java.time.LocalDate;
import java.time.temporal.BusinessDayAdjustment;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
public class WorkDaysCalculator {
private static final BusinessDayAdjustment DEFAULT_ADJUSTMENT = BusinessDayAdjustment.of(ChronoUnit.DAYS);
public static long countWorkDays(LocalDate startDate, LocalDate endDate) {
return computeBusinessDays(startDate.with(TemporalAdjusters.firstDayOfWeek()), endDate)
+ computeBusinessDays(endDate.with(TemporalAdjusters.lastDayOfMonth()), startDate.with(TemporalAdjusters.lastDayOfMonth()));
}
private static long computeBusinessDays(LocalDate start, LocalDate end) {
return Math.toIntExact(BusinessDayCalculator.of(DEFAULT_ADJUSTMENT).count(start, end));
}
// 示例使用
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2023, 1, 1);
LocalDate date2 = LocalDate.of(2023, 1, 31);
System.out.println("从 " + date1 + " 到 " + date2 + " 工作日数: " + countWorkDays(date1, date2));
}
}
```
在这个例子中,我们首先计算了起始日期所在周的第一天到结束日期的所有工作日,然后再加上最后一个月的第一天到结束一天的工作日。注意,这仅包括常规的工作日,不考虑节假日。
阅读全文