写一个 js 函数计算两个时间段内排除掉节假日剩下的时间
时间: 2023-08-03 15:05:50 浏览: 81
首先,需要一个能够返回两个日期之间所有日期的函数,可以写成如下形式:
```javascript
function getDatesBetween(startDate, endDate) {
const dates = [];
const currentDate = new Date(startDate);
while (currentDate <= endDate) {
dates.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
}
```
接下来,需要一个能够判断某个日期是否为节假日的函数,可以使用第三方的节假日 API 或自己维护一个节假日列表进行判断。
最后,可以写出计算排除节假日后剩余时间的函数:
```javascript
async function getWorkingTimeBetween(startDate, endDate) {
const dates = getDatesBetween(startDate, endDate);
const holidays = []; // 节假日列表,可以自己维护或从第三方 API 获取
let workingTime = 0;
for (const date of dates) {
if (date.getDay() === 0 || date.getDay() === 6 || holidays.includes(date)) {
// 周末或节假日不计入工作时间
continue;
}
// 工作时间为每天 9:00 到 18:00
const start = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 9, 0, 0);
const end = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 18, 0, 0);
if (startDate <= end && endDate >= start) {
// 如果跨越了起始时间和结束时间,则只计算部分时间
const overlapStart = startDate > start ? new Date(startDate) : start;
const overlapEnd = endDate < end ? new Date(endDate) : end;
workingTime += (overlapEnd - overlapStart) / (1000 * 60 * 60);
} else if (date >= startDate && date <= endDate) {
// 如果没有跨越起始时间和结束时间,则计算一整天的工作时间
workingTime += 9;
}
}
return workingTime;
}
```
这个函数会返回两个日期之间排除节假日后剩余的工作时间,单位为小时。注意上面的代码只是一个示例,实际应用中可能需要根据具体业务需求进行调整。
阅读全文