Possible Duplicate:
Javascript function to add X months to a date
I’d like to add 2 months to a user-input end date. How can I add 2 months to the end date and display it?
/**
* Click "Cal" on end date
*/
function getEndDate() {
if(!document.getElementById('startdate').value.length) {
alert("Start date must be set first.");
}
else {
prevEndDate = document.getElementById('enddate').value;
displayCalendar(document.forms[0].enddate,'yyyy/mm/dd',
document.getElementById('enddatebutton'));
}
}
/**
* Click "Cal" on expiry date
*/
function getExpiryDate() {
if(!document.getElementById('enddate').value.length) {
alert("End date must be set first.");
}
else {
prevExpiryDate = document.getElementById('expirydate').value;
displayCalendar(document.forms[0].expirydate,'yyyy/mm/dd',
document.getElementById('expirydatebutton'));
}
}
Any help is appreciated. Thanks!
You need to get business rules for adding months. The simple solution is:
However, that will change 31 July to 31 September, which will be converted to 1 October. Also, 31 January plus 1 month is 31 February which will be converted to 2 or 3 March depending on whether it’s a leap year or not.
You might expect the first to be 30 September and the second to be 28 or 29 February (depending on whether it’s a leap year or not).
So if you want “end of months” be observed, you need to do something like:
But check with whoever is responsible for the business rules that that is what they want.
Edit
The above works well, but in response to McShaman’s comment here is a version with a simpler check for the month roll–over: