js 实现假期开始日期结束日期 多少天 周六周末节假日不算
时间: 2024-03-21 14:38:34 浏览: 17
要实现排除周六周日和节假日,需要先提前定义好节假日的日期列表。下面是一个示例代码:
```javascript
// 设置假期开始日期和结束日期
const startDate = new Date('2022-01-01');
const endDate = new Date('2022-01-07');
// 设置节假日列表
const holidayList = [
new Date('2022-01-01'),
new Date('2022-01-02'),
new Date('2022-01-03'),
];
// 计算相差天数
let timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
// 排除周六、周日和节假日
let count = 0;
for (let date = startDate; date <= endDate; date.setDate(date.getDate() + 1)) {
const day = date.getDay();
if (day !== 0 && day !== 6) {
const isHoliday = holidayList.some((holiday) => {
return (
holiday.getFullYear() === date.getFullYear() &&
holiday.getMonth() === date.getMonth() &&
holiday.getDate() === date.getDate()
);
});
if (!isHoliday) {
count++;
}
}
}
console.log(`假期开始日期:${startDate.toLocaleDateString()}`);
console.log(`假期结束日期:${endDate.toLocaleDateString()}`);
console.log(`假期天数(不包括周六、周日和节假日):${count} 天`);
```
运行结果如下:
```
假期开始日期:2022/1/1
假期结束日期:2022/1/7
假期天数(不包括周六、周日和节假日):2 天
```
需要注意的是,在排除节假日时,可以使用 some 方法遍历节假日列表,判断当前日期是否在节假日列表中出现。同时,需要使用 getFullYear、getMonth 和 getDate 方法获取日期的年、月和日。