18

How can I use JavaScript to add working days (i.e. Mon - Friday) automatically adding weekends where necessary?

So if I were to add 5 working days to today (Tue. 22nd Nov. 2016) the result should be "Tue. 29th Nov. 2016" and not "Sun. 27th Nov. 2016".

6 Answers 6

25

It is possible to use Date's setDate function (in combination with getDate) to add days onto a date i.e. -

var myDate = new Date(); // Tue 22/11/2016
myDate.setDate(myDate.getDate() + 3); // Fri 25/11/2016

So once you've calculated the number of weekend days within the workdays period you can add that and the required number of workdays to the start date to get the final date.

This function should work though obviously this will not take account of national holidays -

function addWorkDays(startDate, days) {
    if(isNaN(days)) {
        console.log("Value provided for \"days\" was not a number");
        return
    }
    if(!(startDate instanceof Date)) {
        console.log("Value provided for \"startDate\" was not a Date object");
        return
    }
    // Get the day of the week as a number (0 = Sunday, 1 = Monday, .... 6 = Saturday)
    var dow = startDate.getDay();
    var daysToAdd = parseInt(days);
    // If the current day is Sunday add one day
    if (dow == 0)
        daysToAdd++;
    // If the start date plus the additional days falls on or after the closest Saturday calculate weekends
    if (dow + daysToAdd >= 6) {
        //Subtract days in current working week from work days
        var remainingWorkDays = daysToAdd - (5 - dow);
        //Add current working week's weekend
        daysToAdd += 2;
        if (remainingWorkDays > 5) {
            //Add two days for each working week by calculating how many weeks are included
            daysToAdd += 2 * Math.floor(remainingWorkDays / 5);
            //Exclude final weekend if remainingWorkDays resolves to an exact number of weeks
            if (remainingWorkDays % 5 == 0)
                daysToAdd -= 2;
        }
    }
    startDate.setDate(startDate.getDate() + daysToAdd);
    return startDate;
}

//And use it like so (months are zero based)
var today = new Date(2016, 10, 22);
today = addWorkDays(today, 5); // Tue Nov 29 2016 00:00:00 GMT+0000 (GMT Standard Time)

It could also be added to the Date prototype -

Date.prototype.addWorkDays = function (days) {
    if(isNaN(days)) {
        console.log("Value provided for \"days\" was not a number");
        return
    }

    // Get the day of the week as a number (0 = Sunday, 1 = Monday, .... 6 = Saturday)
    var dow = this.getDay();
    var daysToAdd = parseInt(days);
    // If the current day is Sunday add one day
    if (dow == 0) {
        daysToAdd++;
    }
    // If the start date plus the additional days falls on or after the closest Saturday calculate weekends
    if (dow + daysToAdd >= 6) {
        //Subtract days in current working week from work days
        var remainingWorkDays = daysToAdd - (5 - dow);
        //Add current working week's weekend
        daysToAdd += 2;
        if (remainingWorkDays > 5) {
            //Add two days for each working week by calculating how many weeks are included
            daysToAdd += 2 * Math.floor(remainingWorkDays / 5);
            //Exclude final weekend if the remainingWorkDays resolves to an exact number of weeks
            if (remainingWorkDays % 5 == 0)
                daysToAdd -= 2;
        }
    }
    this.setDate(this.getDate() + daysToAdd);
};

//And use it like so (months are zero based)
var today = new Date(2016, 10, 22)
today.addWorkDays(5); // Tue Nov 29 2016 00:00:00 GMT+0000 (GMT Standard Time)
3
  • For the prototype, instead of this.setDate(this.getDate() + daysToAdd);, I used return this.addDays(daysToAdd); because it more closely resembles the way the native Date.prototype.addDays works.
    – CSquared
    Sep 16, 2019 at 16:10
  • @CSquared native Date.prototype.addDays? I'm not aware of a native addDays method and it's not documented on MDN - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…; are you sure it hasn't been added by another JS file in your solution?
    – John C
    Sep 17, 2019 at 8:25
  • I stand corrected, it isn't native. In my case it was coming from the Kendo UI library. I wish it were native.
    – CSquared
    Oct 1, 2019 at 13:57
3

If it's for adding a few days, not thousands of days, then this is easier and more readable:

const currentDate = new Date('2021-11-18');
console.log(currentDate.toString()); // "Thu Nov 18 2021 00:00:00 GMT+0000"

const numToAdd = 5;

for (let i = 1; i <= numToAdd; i++) {
  currentDate.setDate(currentDate.getDate() + 1);
  if (currentDate.getDay() === 6) {
    currentDate.setDate(currentDate.getDate() + 2);
  }
  else if (currentDate.getDay() === 0) {
    currentDate.setDate(currentDate.getDate() + 1);
  }
}

console.log(currentDate.toString()); // "Thu Nov 25 2021 00:00:00 GMT+0000"
1
  • I think this is the best solution, it's much more straight-forward and easier to understand. I edited your code slightly, Mark, hope that's okay. Nov 18, 2021 at 10:29
2

I think you can use moment-business-days.

Example:

// 22-11-2016 is Tuesday, DD-MM-YYYY is the format 
moment('22-11-2016', 'DD-MM-YYYY').businessAdd(5)._d // Tue Nov 29 2016 00:00:00 GMT-0600 (CST) 
1

const date = new Date('2000-02-02')
const daysToAdd = mapToWorkdays(date, 37)

date.setUTCDate(date.getUTCDate() + daysToAdd)

console.log( date.toISOString().split('T')[0] )
// prints 2000-03-24

/**
 * @param {Date} date starting date
 * @param {number} add number of workdays to add
 * @return {number} total number of days to add to reach correct date
 */
function mapToWorkdays(date, add) {
  const wd = weekday(date)
  
  let r = Math.trunc(add / 5) * 2
  const rem = add % 5

  if (wd > 4) r += (6-wd)
  else if (wd+rem > 4) r += 2

  return add + r
}

/**
 * @param {Date} date
 * @return {number} day of the week in range of 0..6 (monday..sunday)
 */
function weekday(date) { return (date.getUTCDay()+ 6) % 7 }

2
  • 2
    I think this solution is not correct. For Saturday and Sunday the result of mapToWorkdays is not correct when the add parameter is a multiple of 5. I have compared with the results returned by Excel and that confirms these specific results are wrong. I've replaced the line if (wd > 4) r += (6-wd) by by if (wd > 4) { r += (6 - wd) if (rem === 0) r-= 2 } to correct this. Check out here jsfiddle.net/Roebie/vx2prqj0/16 The earlier solutions are even more wrong, but I haven't taken the time to fix them.
    – Roebie
    Feb 2, 2021 at 13:48
  • @Roebie I think the only issue is that it should be r += (7 - wd). If you call the function from sat/sun and pass add:0 the result should still return 2 for saturday, and 1 for sunday. The first if is actually saying: "If we're on weekends, adjust everything to first of the week (a.k.a 0)". and else-if says: "If we're on weekdays, and with add%5 we'll end-up in weekend, we should add two more days" Jan 26, 2022 at 20:48
0

Updated above script to also subtract workdays if negative days are given...

function addWorkDays(startDate, days) {
    var isAddingDays = (days > 0);
    var isDaysToAddMoreThanWeek = (days > 5 || days < -5);

    if (isNaN(days)) {
        console.log("Value provided for \"days\" was not a number");
        return
    }
    if (!(startDate instanceof Date)) {
        console.log("Value provided for \"startDate\" was not a Date object");
        return
    }
    var dow = startDate.getDay();
    var daysToAdd = parseInt(days);

    if ((dow === 0 && isAddingDays) || (dow === 6 && !isAddingDays)) {
        daysToAdd = daysToAdd + (1 * (isAddingDays ? 1 : -1));
    } else if ((dow === 6 && isAddingDays) || (dow === 0 && !isAddingDays)) {
        daysToAdd = daysToAdd + (2 * (isAddingDays ? 1 : -1));
    }

    if (isDaysToAddMoreThanWeek) {
        daysToAdd = daysToAdd + (2 * (Math.floor(days / 5)));

        if (days % 5 != 0)
            daysToAdd = daysToAdd + (2 * (isAddingDays ?  -1 : 1));
    }

    startDate.setDate(startDate.getDate() + daysToAdd);
    var newDate = moment(startDate).format('MM/DD/YYYY');
    return newDate;
}
1
  • Doesn't work when starting from a Tuesday and adding 5 days (it returns the following Sunday).
    – assylias
    Apr 13, 2021 at 10:53
0

This is my simplyest final solution for me:

function addWorkDays(startDate, daysToAdd) {
  let dw=startDate.getDay(); //* see note
  startDate.setDate(startDate.getDate()-((dw==6)?1:(dw==0)?2:0)); //*
  var avance = 2 * Math.floor(daysToAdd / 5); //add 2 days for each 5 workdays
  var exceso = (daysToAdd % 5) + startDate.getDay() ;
  if (exceso>=6) avance +=2 ; 
  startDate.setDate(startDate.getDate() + daysToAdd + avance);
  return startDate;
}

// If used only with business day dates, the first two lines are not required

2
  • Doesn't handle Sat & Sundays well. If you do +1 work day on Friday it gives you Monday on Saturday it gives you Tuesday and on Sunday it gives you Monday
    – ScrapeHeap
    Sep 1, 2022 at 13:53
  • Hello, ScrapHead. In order to be short, this code worked on business days. If you want it to work on holidays as well, just add something else at the beginning. I have completed the code for this case.
    – Emilio CR
    Sep 2, 2022 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.