Skip to content

Instantly share code, notes, and snippets.

@sholsinger
Created April 18, 2011 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sholsinger/926288 to your computer and use it in GitHub Desktop.
Save sholsinger/926288 to your computer and use it in GitHub Desktop.
A JavaScript module to extend the Date prototype to provide an easy method for adding to or subtracting from a Date instance in business days.
if(Number.prototype.mod === undefined)
{
Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
}
}
if(Date.prototype.addBusinessDays === undefined)
{
Date.prototype.addBusinessDays = function(dd) {
var weeks = (dd >= 0) ? Math.floor(dd/5): Math.ceil(dd/5);
var days = dd % 5;
var day = this.getDay();
if (day === 6 && days > -1)
{
if (days === 0)
{
days-=2;
day+=2;
}
days++;
day -= 5;
}
if (day === 0 && days < 1)
{
if (days === 0)
{
days+=2;
day-=2;
}
days--;
day += 5;
}
if (day + days > 5){days += 2};
if (day + days < 1){days -= 2};
this.setDate(this.getDate()+weeks*7+days);
}
}
@sholsinger
Copy link
Author

My primary contribution to this piece of history from http://javascript.about.com/library/blbusdayadd.htm can be found on line 10. The original implementation just did a Math.floor() on dd/5 which works great until you're subtracting business days and now all of a sudden the "next business day" is 1 day past your target. floor() behaves differently for negative numbers. For this we want more of a ceil() effect in that situation. Oddly enough, VBScript's Fix() method behaves as JS's ceil() for negative numbers and like JS's floor() for positive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment