js如何去掉周末并且计算出本月上班天数
时间: 2024-10-18 11:17:52 浏览: 57
在JavaScript中,你可以通过以下步骤来去掉周末并计算本月的上班天数:
1. 首先,获取当前月份的日期范围。可以使用`new Date()`创建当前日期,然后使用`getMonth()`和`getDate()`方法得到当月第一天和最后一天。
```javascript
const currentDate = new Date();
const monthStart = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
const monthEnd = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
```
2. 创建一个函数来检查给定日期是否为工作日。通常,你可以假设周一至周五是工作日。这里我们可以借助`isNaN()`和数组索引来排除周末。
```javascript
function isWorkDay(date) {
const daysOfWeek = ['Saturday', 'Sunday'];
return !daysOfWeek.includes(new Date(date).toLocaleDateString('en-US', { weekday: 'long' }));
}
```
3. 然后遍历这个月份的每一天,调用`isWorkDay()`函数,并累加上班天数。
```javascript
let workingDaysCount = 0;
for (let date = monthStart; date <= monthEnd; date.setDate(date.getDate() + 1)) {
if (isWorkDay(date)) {
workingDaysCount++;
}
}
```
4. 最后,`workingDaysCount`就存储了本月的工作天数。
完整的代码示例:
```javascript
function countWorkingDaysInMonth() {
const currentDate = new Date();
const monthStart = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
const monthEnd = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
let workingDaysCount = 0;
for (let date = monthStart; date <= monthEnd; date.setDate(date.getDate() + 1)) {
if (isWorkDay(date)) {
workingDaysCount++;
}
}
return workingDaysCount;
}
// 计算并打印结果
console.log(countWorkingDaysInMonth());
阅读全文
相关推荐












