Skip to content Skip to sidebar Skip to footer

Add Working Days To A Date Using Javascript

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) th

Solution 1:

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

var myDate = newDate(); // 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 -

functionaddWorkDays(startDate, days) {
    if(isNaN(days)) {
        console.log("Value provided for \"days\" was not a number");
        return
    }
    if(!(startDate instanceofDate)) {
        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 dayif (dow == 0)
        daysToAdd++;
    // If the start date plus the additional days falls on or after the closest Saturday calculate weekendsif (dow + daysToAdd >= 6) {
        //Subtract days in current working week from work daysvar 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 weeksif (remainingWorkDays % 5 == 0)
                daysToAdd -= 2;
        }
    }
    startDate.setDate(startDate.getDate() + daysToAdd);
    return startDate;
}

//And use it like so (months are zero based)var today = newDate(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 dayif (dow == 0) {
        daysToAdd++;
    }
    // If the start date plus the additional days falls on or after the closest Saturday calculate weekendsif (dow + daysToAdd >= 6) {
        //Subtract days in current working week from work daysvar 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 weeksif (remainingWorkDays % 5 == 0)
                daysToAdd -= 2;
        }
    }
    this.setDate(this.getDate() + daysToAdd);
};

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

Solution 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) 

Solution 3:

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

const currentDate = newDate('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);
  }
  elseif (currentDate.getDay() === 0) {
    currentDate.setDate(currentDate.getDate() + 1);
  }
}

console.log(currentDate.toString()); // "Thu Nov 25 2021 00:00:00 GMT+0000"

Solution 4:

const date = newDate('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
 */functionmapToWorkdays(date, add) {
  const wd = weekday(date)
  
  let r = Math.trunc(add / 5) * 2const rem = add % 5if (wd > 4) r += (6-wd)
  elseif (wd+rem > 4) r += 2return add + r
}

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

Solution 5:

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

functionaddWorkDays(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 instanceofDate)) {
        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));
    } elseif ((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;
}

Post a Comment for "Add Working Days To A Date Using Javascript"