# Add WeekDays to Date

Will the below code work for adding Weekdays in all possible scenarios? eg, If I add 4 days to a "Thursday", the result should be next "Wednesday". Adding 1 day to a "Friday", "Saturday" or "Sunday" should be the next "Monday".

I am trying to get the nth working day (weekday) after a given day.

var addOneDay=function(date) {
var result = new Date(date.getTime());
result.setDate(result.getDate() + 1);
return result;
};

var addWeekDays = function(date,days) {
var result = new Date(date.getTime());
for (var i = 0; i < days; i++) {
if (result.getDay()=== 6 || result.getDay()=== 0) i--;
};
return result;
};

var date = new Date(2016,1,18);

• Welcome to Code Review! Date-Time manipulation is usually tricky, so it is hard to say if it will work in every possible scenario, you should try to test it. That said, I'm sure we can help you improve your code! Feb 10, 2016 at 18:25
• It seems "all possible scenarios" could be covered with.... 7 tests? Feb 10, 2016 at 18:50
• @Mat'sMug To be thorough, 49 tests, maybe much more. Feb 10, 2016 at 18:53
• @Mat'sMug Barring a calendar reform 7 tests might be "fine" Feb 10, 2016 at 18:55

What is the expected behaviour if you add one weekday to a Saturday? Possible answers are: throw an exception, behavior is undefined, Monday, or Tuesday. Make a decision, and document it.

The use of var funcName = function(…) { … } is a bit unconventional compared to function funcName(…) { … }, but it's not wrong.

Other than that, I think that the code looks correct. For a more efficient way to add large intervals, you could add a number of integral weeks (7 * Math.floor(days / 5)) and advance the remainder (days % 5) the slow way.