Java 计算工作日,休假,调休,调班等
时间: 2024-02-26 18:03:46 浏览: 83
实现计算工作日、休假、调休和调班等功能需要考虑到节假日、周末以及调休和调班等因素,可以使用 Java 中的日期时间类 `java.time` 来实现。
下面是一个简单的 Java 代码示例,演示如何计算两个日期之间的工作日天数:
```java
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class WorkingDaysCalculator {
// 计算两个日期之间的工作日天数
public static int getWorkingDays(LocalDate startDate, LocalDate endDate) {
int workingDays = 0;
LocalDate date = startDate;
while (!date.isAfter(endDate)) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
workingDays++;
}
date = date.plusDays(1);
}
return workingDays;
}
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2021, 9, 1);
LocalDate endDate = LocalDate.of(2021, 9, 30);
int workingDays = getWorkingDays(startDate, endDate);
System.out.println("工作日天数:" + workingDays);
}
}
```
接下来,我们可以在此基础上扩展代码,以实现休假、调休和调班等功能。例如,我们可以定义一个列表,记录所有的节假日和调休日期,然后在计算工作日天数时排除这些日期,如下所示:
```java
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
public class WorkingDaysCalculator {
// 计算两个日期之间的工作日天数
public static int getWorkingDays(LocalDate startDate, LocalDate endDate) {
int workingDays = 0;
LocalDate date = startDate;
while (!date.isAfter(endDate)) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY && !isHoliday(date)) {
workingDays++;
}
date = date.plusDays(1);
}
return workingDays;
}
// 判断指定日期是否是节假日或调休日期
public static boolean isHoliday(LocalDate date) {
List<LocalDate> holidays = new ArrayList<>();
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)); // 调休
return holidays.contains(date);
}
public static void main(String[] args) {
LocalDate startDate = LocalDate.of(2021, 9, 1);
LocalDate endDate = LocalDate.of(2021, 10, 10);
int workingDays = getWorkingDays(startDate, endDate);
System.out.println("工作日天数:" + workingDays);
}
}
```
这段代码中,我们定义了一个 `isHoliday()` 方法,用于判断指定日期是否是节假日或调休日期。在 `getWorkingDays()` 方法中,我们在计算工作日天数时,排除了这些日期,从而实现了计算工作日天数、休假、调休和调班等功能。
阅读全文