java实现在一个时间段去除周末和法定节假日
时间: 2024-09-23 07:12:50 浏览: 63
在 Java 中,实现一个功能来排除指定时间段内的周末(周六和周日)以及法定节假日,通常可以结合 Calendar 类、GregorianCalendar 类和 Date 接口来进行。以下是一个简单的示例:
```java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class WorkDaysCalculator {
private static final String[] HOLIDAYS; // 假定这里有一个包含节假日日期的数组
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDate = "2023-01-01";
String endDate = "2023-01-31";
try {
Date start = sdf.parse(startDate);
Date end = sdf.parse(endDate);
for (Date date = start; !date.after(end); date = addWorkDays(date)) {
if (!isWeekend(date) && !isHoliday(date)) {
System.out.println(sdf.format(date)); // 输出工作日日期
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean isWeekend(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
}
private static boolean isHoliday(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return containsHoliday(calendar.getTime());
}
private static boolean containsHoliday(Date date) {
for (String holiday : HOLIDAYS) {
try {
Date holidayDate = sdf.parse(holiday);
if (holidayDate.equals(date)) return true;
} catch (Exception e) {} // 忽略无效的假日字符串
}
return false;
}
private static Date addWorkDays(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
while (isWeekend(calendar.getTime()) || isHoliday(calendar.getTime())) {
calendar.add(Calendar.DATE, 1);
}
return calendar.getTime();
}
}
```
在这个示例中,我们首先定义了一个包含节假日日期的静态数组 `HOLIDAYS`,然后通过 `isWeekend` 和 `isHoliday` 方法检查日期是否为周末或法定节假日。`addWorkDays` 方法会递增日期直到遇到工作日。
阅读全文