MOCKSTACKS
EN
Questions And Answers

More Tutorials









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

Output



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.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.