Increment a Date Object

suggest change

setDate changes the local day of the month. A value past the end of the month rolls into the next month. The comments below are toString() in US Eastern Daylight Time. Another time zone prints a different zone name.

const checkoutDate = new Date(2016, 6, 21, 10, 5, 13); // Thu Jul 21 2016 10:05:13 GMT-0400 (EDT)

checkoutDate.setDate(checkoutDate.getDate() + 1);

console.log(checkoutDate); // Fri Jul 22 2016 10:05:13 GMT-0400 (EDT)

Twelve days later is in August:

const checkoutDate = new Date(2016, 6, 21, 10, 5, 13); // Thu Jul 21 2016 10:05:13 GMT-0400 (EDT)
checkoutDate.setDate(checkoutDate.getDate() + 12);
console.log(checkoutDate); // Tue Aug 02 2016 10:05:13 GMT-0400 (EDT)

The same overflow applies to other setters, such as setMonth(getMonth() + 1) and setHours(getHours() + 1). Around a daylight-saving change, adding a day can also change the clock time.

Adding Work Days

Adding Monday–Friday work days needs to skip weekends. The old day-count formula was wrong when the start date was a Saturday or a Sunday. This version walks forward one calendar day at a time, counts only weekdays, and mutates startDate. It does not skip public holidays.

function addWorkDays(startDate, days) {
    let remaining = days;
    while (remaining > 0) {
        startDate.setDate(startDate.getDate() + 1);
        const dow = startDate.getDay(); // 0 = Sunday, 6 = Saturday
        if (dow !== 0 && dow !== 6) {
            remaining--;
        }
    }
    return startDate;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents