Created
April 18, 2011 21:58
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()
ondd/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 aceil()
effect in that situation. Oddly enough, VBScript'sFix()
method behaves as JS'sceil()
for negative numbers and like JS'sfloor()
for positive.