java怎么计算工作日
时间: 2024-05-12 21:12:56 浏览: 69
Java计算工作日
在Java中计算工作日可以使用Java 8中的java.time包中的工具类来实现。以下是一种实现方式:
1. 首先,需要定义一个工作日的列表,包含每周的周末和节假日。可以通过代码动态生成或者从数据库或配置文件中读取。
2. 然后,可以使用java.time.LocalDate类来计算两个日期之间的工作日数量。可以使用该类的工具方法isWeekend()检查一个日期是否为周末,使用工作日列表检查是否为节假日。
3. 最后,使用工作日数量计算两个日期之间的工作日差值。
以下是一个示例代码:
```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 Set<LocalDate> holidays;
public WorkdayCalculator(Set<LocalDate> holidays) {
this.holidays = holidays;
}
public long getWorkdays(LocalDate start, LocalDate end) {
long days = ChronoUnit.DAYS.between(start, end);
int weekends = getWeekendDays(start, end);
int holidays = getHolidays(start, end);
return days - weekends - holidays;
}
private int getWeekendDays(LocalDate start, LocalDate end) {
int weekends = 0;
LocalDate date = start;
while (!date.isAfter(end)) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) {
weekends++;
}
date = date.plusDays(1);
}
return weekends;
}
private int getHolidays(LocalDate start, LocalDate end) {
int holidays = 0;
LocalDate date = start;
while (!date.isAfter(end)) {
if (this.holidays.contains(date)) {
holidays++;
}
date = date.plusDays(1);
}
return holidays;
}
public static void main(String[] args) {
Set<LocalDate> holidays = new HashSet<>();
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, 15));
holidays.add(LocalDate.of(2021, 2, 16));
holidays.add(LocalDate.of(2021, 4, 5));
holidays.add(LocalDate.of(2021, 5, 1));
holidays.add(LocalDate.of(2021, 6, 14));
holidays.add(LocalDate.of(2021, 9, 20));
holidays.add(LocalDate.of(2021, 10, 1));
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));
holidays.add(LocalDate.of(2021, 10, 8));
WorkdayCalculator calculator = new WorkdayCalculator(holidays);
LocalDate start = LocalDate.of(2021, 1, 1);
LocalDate end = LocalDate.of(2021, 10, 8);
long workdays = calculator.getWorkdays(start, end);
System.out.println("工作日数量: " + workdays);
}
}
```
上述代码中,首先定义了一个节假日列表,然后创建了一个WorkdayCalculator对象,该对象包含了一个节假日列表,以便在计算工作日时使用。最后调用getWorkdays()方法计算两个日期之间的工作日数量。
阅读全文