
首先,我们需要定义一个类来存储工作时间和节假日信息。在这个例子中,我们假设工作日是从周一到周五,法定节假日是一个静态的字符串数组。
java
public class WorkTimeCalculator {
// 定义工作日数组
private static final String[] WEEKEND = {"Saturday", "Sunday"};
// 定义法定节假日数组
private static final String[] HOLIDAYS = {
"New Year's Day", "Chinese New Year's Eve", "Chinese New Year", "Qingming Festival",
"Labour Day", "Dragon Boat Festival", "Mid-Autumn Festival", "National Day"
};
// 计算工作日的方法
public static int calculateWorkDays(String startDate, String endDate) {
// 初始化工作日计数器
int workDays = 0;
// 创建两个日期对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date start = sdf.parse(startDate);
Date end = sdf.parse(endDate);
// 循环遍历两个日期之间的每一天
while (start.before(end) || start.equals(end)) {
// 获取当前日期
String currentDate = sdf.format(start);
// 检查当前日期是否在工作日、周末或法定节假日中
if (!isWeekend(currentDate) && !isHoliday(currentDate)) {
workDays++;
}
// 移动到下一天
start = addDays(start, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return workDays;
}
// 判断当前日期是否在工作日
private static boolean isWeekend(String date) {
Calendar cal = Calendar.getInstance();
cal.setTime(
更多文章请关注《万象专栏》
转载请注明出处:https://www.wanxiangsucai.com/read/cv183369