0
如何根据问题调整代码以考虑国家法定节假日。通过考虑假日计算JavaScript的工作日
Getting Working Days Using Javascript
我知道我会需要日期它们是假期,但需要被添加到逻辑是什么阵列?
如何根据问题调整代码以考虑国家法定节假日。通过考虑假日计算JavaScript的工作日
Getting Working Days Using Javascript
我知道我会需要日期它们是假期,但需要被添加到逻辑是什么阵列?
获得假期阵列实际上可能不是故事中最简单的部分。
无论如何,我会假设你最终会以[ year, month, day ]
格式结束日期列表。存储完整的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')));
你需要发布一些代码显示你到目前为止,否则你只是要求某人为你建立这个。以下是各种美国公众假期的摘要:http://www.webcal.fi/en-US/other_file_formats.php – Toby