[原创]JS端计算一段时间内工作日的天数,排除周末和法定节假日,同时考虑到调休日...
时间: 2024-03-16 22:41:31 浏览: 16
这个问题需要比较复杂的逻辑来实现。以下是一种可能的解决方案:
1. 获取指定时间段内的所有日期列表。
2. 遍历日期列表,判断每个日期是否是周末或法定节假日,如果是则排除。
3. 判断调休日是否需要工作,如果需要工作则将其计入工作日天数。
4. 返回工作日天数。
具体实现过程如下:
1. 获取指定时间段内的日期列表。
```javascript
function getDates(startDate, endDate) {
const dates = []
let currentDate = startDate
while (currentDate <= endDate) {
dates.push(new Date(currentDate))
currentDate.setDate(currentDate.getDate() + 1)
}
return dates
}
const startDate = new Date('2021-04-01')
const endDate = new Date('2021-04-30')
const dates = getDates(startDate, endDate)
```
2. 判断每个日期是否是周末或法定节假日,如果是则排除。
这里需要一个判断日期是否是周末的函数和一个判断日期是否是法定节假日的函数。这些函数可以通过调用日历 API 或者自己维护一个节假日列表来实现。
```javascript
function isWeekend(date) {
const day = date.getDay()
return day === 0 || day === 6
}
function isHoliday(date) {
// 判断日期是否是法定节假日
// ...
}
const workDays = dates.filter(date => !isWeekend(date) && !isHoliday(date))
```
3. 判断调休日是否需要工作,如果需要工作则将其计入工作日天数。
这里需要一个判断日期是否是调休工作日的函数。调休工作日可以通过日历 API 或者自己维护一个调休工作日列表来实现。
```javascript
function isWorkday(date) {
// 判断日期是否是调休工作日
// ...
}
const workDaysCount = workDays.reduce((count, date) => {
if (isWorkday(date)) {
return count + 1
} else {
return count
}
}, 0)
```
4. 返回工作日天数。
```javascript
console.log(workDaysCount)
```
完整代码如下:
```javascript
function getDates(startDate, endDate) {
const dates = []
let currentDate = startDate
while (currentDate <= endDate) {
dates.push(new Date(currentDate))
currentDate.setDate(currentDate.getDate() + 1)
}
return dates
}
function isWeekend(date) {
const day = date.getDay()
return day === 0 || day === 6
}
function isHoliday(date) {
// 判断日期是否是法定节假日
// ...
}
function isWorkday(date) {
// 判断日期是否是调休工作日
// ...
}
function getWorkDaysCount(startDate, endDate) {
const dates = getDates(startDate, endDate)
const workDays = dates.filter(date => !isWeekend(date) && !isHoliday(date))
const workDaysCount = workDays.reduce((count, date) => {
if (isWorkday(date)) {
return count + 1
} else {
return count
}
}, 0)
return workDaysCount
}
const startDate = new Date('2021-04-01')
const endDate = new Date('2021-04-30')
const workDaysCount = getWorkDaysCount(startDate, endDate)
console.log(workDaysCount)
```