最佳答案
获取一系列假期实际上可能不是故事中最简单的部分。
无论如何,我假设您最终会得到一个 [ 年、月、日 ]
格式的日期数组。还有另一种可能性是存储完整的 Date
对象,这可能更适合也可能不适合,具体取决于您的导入方法。
下面是一个非常简化且明显不完整的:
const holidays = [
[ 2015, 1, 1 ], [ 2015, 1, 19 ], [ 2015, 7, 4 ], [ 2015, 12, 25 ],
[ 2016, 1, 1 ], [ 2016, 1, 18 ], [ 2016, 7, 4 ], [ 2016, 12, 25 ],
[ 2017, 1, 1 ], [ 2017, 1, 16 ], [ 2017, 7, 4 ], [ 2017, 12, 25 ]
];
这里有一些代码可以帮助您入门:
const holidays = [
[ 2015, 1, 1 ], [ 2015, 1, 19 ], [ 2015, 7, 4 ], [ 2015, 12, 25 ],
[ 2016, 1, 1 ], [ 2016, 1, 18 ], [ 2016, 7, 4 ], [ 2016, 12, 25 ],
[ 2017, 1, 1 ], [ 2017, 1, 16 ], [ 2017, 7, 4 ], [ 2017, 12, 25 ]
];
function isHoliday(ts) {
var year = ts.getFullYear(),
month = ts.getMonth(),
day = ts.getDate();
return holidays.some(function(d) {
return d[0] == year && d[1] == month + 1 && d[2] == day;
});
}
function getWorkingDays(ts, end) {
for(var cnt = 0; ts.getTime() <= end.getTime(); ts.setDate(ts.getDate() + 1)) {
// increment counter if this day is neither a Sunday,
// nor a Saturday, nor a holiday
if(ts.getDay() != 0 && ts.getDay() != 6 && !isHoliday(ts)) {
cnt++;
}
}
return cnt;
}
console.log(getWorkingDays(new Date('2015-12-20'), new Date('2016-01-03')));
console.log(getWorkingDays(new Date('2016-12-20'), new Date('2017-01-03')));
关于javascript - 使用 JavaScript 计算工作日并考虑假期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38589517/