MOCKSTACKS
EN

# 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.

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

// Get the day of the week as a number (0 = Sunday, 1 = Monday, .... 6 = Saturday)
var dow = startDate.getDay();
// If the current day is Sunday add one day
if (dow == 0)
// 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);
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)
}
}
return startDate;
}

### Convert to JSON

var date1 = new Date();
date1.toJSON();

## Conclusion

In this page (written and validated by ) you learned about Javascript Increment a Date Object . What's Next? If you are interested in completing Javascript tutorial, your next topic will be learning about: Javascript Date Comparison.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.