gpt4 book ai didi

javascript - 使用 JavaScript 计算工作日并考虑假期

转载 作者:行者123 更新时间:2023-12-03 06:27:25 24 4
gpt4 key购买 nike

我如何调整该问题中的代码以考虑国家法定节假日。

Getting Working Days Using Javascript

我知道我需要一组假期日期,但是需要在逻辑中添加什么?

最佳答案

获取一系列假期实际上可能不是故事中最简单的部分。

无论如何,我假设您最终会得到一个 [ 年、月、日 ] 格式的日期数组。还有另一种可能性是存储完整的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com