Javascript Increment a Date Object
To increment date objects in JavaScript, we can usually do this:
var checkoutDate = new Date();
checkoutDate.setDate( checkoutDate.getDate() + 1 );
console.log(checkoutDate);
Output
It is possible to use setDate to change the date to a day in the following month by using a value larger than the number of days in the current month -
var checkoutDate = new Date();
checkoutDate.setDate( checkoutDate.getDate() + 12 );
console.log(checkoutDate);
Output
The same applies to other methods such as getHours(), getMonth(),etc.
Adding Work Days
If you wish to add work days (in this case I am assuming Monday - Friday) you can use the setDate function although you need a little extra logic to account for the weekends (obviously this will not take account of national holidays) -
function addWorkDays(startDate, days) {
// Get the day of the week as a number (0 = Sunday, 1 = Monday, .... 6 = Saturday)
var dow = startDate.getDay();
var daysToAdd = 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;
}
Convert to JSON
var date1 = new Date();
date1.toJSON();