Created
January 31, 2015 06:56
-
-
Save mzgoddard/25bf5b54a2a533fd5799 to your computer and use it in GitHub Desktop.
Add a number of workdays to a starting date.
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
// Solution to https://gist.github.com/jmeas/0a713e0b9901a25a32f1. | |
module.exports = function(start, increment) { | |
// Parse the date. | |
var d = new Date(start); | |
// Determine day of week. | |
var day = d.getUTCDay(); | |
// Determine sign. | |
var sign = Math.sign(increment); | |
var absIncrement = Math.abs(increment); | |
var days = 0; | |
// If increment is greater than or less than 0 and day of week is a | |
// weekend, add a signed buffer. | |
if (day === 0 && sign !== 0) { | |
days = 1; | |
} else if (day === 6 && sign === 1) { | |
days = 2; | |
} | |
// Add padding for weekends. | |
var paddedAbsIncrement = absIncrement; | |
if (day !== 0 && day !== 6 && sign > 0) { | |
paddedAbsIncrement += day - 1; | |
} else if (day !== 0 && day !== 6 && sign < 0) { | |
paddedAbsIncrement += 6 - day; | |
} | |
var weekendsInbetween = | |
Math.max(Math.floor(paddedAbsIncrement / 5) - 1, 0) + | |
(paddedAbsIncrement > 5 && paddedAbsIncrement % 5 > 0 ? 1 : 0); | |
// Add the increment and number of weekends. | |
days += absIncrement + weekendsInbetween * 2; | |
// Create a new date. | |
d = new Date(d.valueOf() + 864E5 * days * sign); | |
return d.toISOString().split('T')[0]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment