Reputation: 971
How can I adapt the code in thus question to take into account national holidays.
Getting Working Days Using Javascript
I know I will need an array of dates which are holidays but what needs to be added into the logic ?
Upvotes: 0
Views: 265
Reputation: 6110
Getting the array of holidays may actually not be the easiest part of the story.
Anyway, I'm going to assume that you eventually end up with an array of dates in [ year, month, day ]
format. Storing full Date
objects in there is another possibility, which may or may not be better suited depending on your import method.
Below is a very simplified and obviously incomplete one:
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 ]
];
And here is some code to help you get started:
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')));
Upvotes: 1