patternjavascriptMinor
Add WeekDays to Date
Viewed 0 times
weekdaysadddate
Problem
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.
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++) {
result = addOneDay(result);
if (result.getDay()=== 6 || result.getDay()=== 0) i--;
};
return result;
};
var date = new Date(2016,1,18);
console.log(addWeekDays(date,4));Solution
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
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 (
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.Context
StackExchange Code Review Q#119524, answer score: 2
Revisions (0)
No revisions yet.