写一个 js 函数计算两个时间段内排除掉节假日剩下的时间
时间: 2023-08-03 10:05:50 浏览: 50
好的,我来为您提供一个计算两个时间段内排除掉节假日后剩下的时间的 JavaScript 函数。
首先,我们需要一个能够获取两个日期之间所有日期的函数。可以使用如下代码实现:
```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
const holidays = [
new Date(2022, 0, 1), // 元旦
new Date(2022, 0, 2),
new Date(2022, 0, 3),
new Date(2022, 1, 1), // 春节
new Date(2022, 1, 2),
new Date(2022, 1, 3),
new Date(2022, 1, 4),
new Date(2022, 1, 5),
new Date(2022, 1, 6),
new Date(2022, 1, 7),
new Date(2022, 3, 5), // 清明节
new Date(2022, 4, 1), // 劳动节
new Date(2022, 4, 2),
new Date(2022, 4, 3),
new Date(2022, 5, 1), // 端午节
new Date(2022, 8, 10), // 中秋节
new Date(2022, 9, 1), // 国庆节
new Date(2022, 9, 2),
new Date(2022, 9, 3),
new Date(2022, 9, 4),
new Date(2022, 9, 5),
new Date(2022, 9, 6),
new Date(2022, 9, 7),
new Date(2022, 9, 8),
];
```
最后,我们可以写出计算排除节假日后剩余时间的函数,代码如下:
```javascript
function getWorkingTimeBetween(startDate, endDate) {
const dates = getDatesBetween(startDate, endDate);
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;
}
```
这个函数会返回两个日期之间排除掉节假日后剩余的工作时间,单位为小时。注意,上面的代码只是一个示例,实际应用中可能需要根据具体业务需求进行调整。