Add Business Days
Adding to the Date Object
Adding and subtracting days from a given date is a relatively simple thing to do in JavaScript and is even easier if you add a method to your date objects to do it for you. Adding or subtracting business days is not quite so simple or at least didn't used to be. Now however adding and subtracting business days is just as easy as adding and subtracting days. The only difference is which of the methods you add to your dates that you call to do it.
Here we are going to create an "add business days" method to add to our date objects making it a simple call to be able to add business days to a date (and of course we can subtract business days by adding a negative number of days).
The code that we need to do this is not as simple and straightforward as for just adding days but it isn't any harder for you to implement because I have already written all the code for you so that all you have to do is copy and paste. We'll start by looking at the code itself and then I'll explain a bit about what it does.
return ((this%n)+n)%n;
}
Date.prototype.addBusDays = function(dd) {
var wks = Math.floor(dd/5);
var dys = dd.mod(5);
var dy = this.getDay();
if (dy === 6 && dys > -1) {
if (dys === 0) {dys-=2; dy+=2;}
dys++; dy -= 6;}
if (dy === 0 && dys < 1) {
if (dys === 0) {dys+=2; dy-=2;}
dys--; dy += 6;}
if (dy + dys > 5) dys += 2;
if (dy + dys < 1) dys -= 2;
this.setDate(this.getDate()+wks*7+dys);
}
With that added to your script you can then call addBusDays(nn) to add or subtract nn business days from any date. For example to add 9 business days to a date we use:
due.addBusDays(9);
After calling that code the value in the due date field is .
The main part of the processing basically works out the whole number of weeks by dividing the days by five (since there are five business days in a week) and then multiplying that by seven and adding back the leftover days. The vast majority of the script is then adusting for if the odd days take us over a weekend (where we need to add two extra days) or if the period ends on a weekend where it is then it is necessary to adjust the date to the next business day. Also the tests required for handling an end date on the weekend needs to perform differently depending on whether we are adding or subtracting days (since if we are adding we need to move to the next Monday while if we are subtracting we need to move to the prior Friday).
This script takes care of all these options so that you can easily just plug in the number of business days knowing you'll get the right answer. The only complication this script doesn't cater for is where you have week days that are not business days. Since the script has no way to tell when those occur it simply assumes that all weeks contain five business days and calculates on that basis.

