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