Answer the question
In order to leave comments, you need to log in
Adding an integer number of months to a date in JS?
Not very strong in JS, but the task needs to be solved using JS tools. The task itself:
At the input there is a date, for example, in the format dd.mm.yyyy and an integer number of full months to be added.
The algorithm is as follows:
Date = Date + N months - 1 day;
Example:
At the input on January 1, we add 1 months, at the output on January 31
At the input on January 1, we add 2 months, at the output on February 28 (low) or February 29 (high)
After a little searching, I came across the Date class, extended it according to the manual:
Date.prototype.addMonths= function(m) {<br/>
var d = this.getDate();<br/>
this.setMonth( this.getMonth() + m );<br/>
<br/>
if (this.getDate() < d )<br/>
this.setDate( 0 );<br/>
<br/>
this.setDate( this.getDate()-1 );<br/>
<br/>
};
var beginDate = '01.08.2011';<br/>
var months = 1;<br/>
<br/>
var dateArr = beginDate.split( '.' );<br/>
var d = dateArr[0] * 1;<br/>
var m = dateArr[1] * 1;<br/>
var y = dateArr[2] * 1;<br/>
<br/>
var newDate = new Date(y, m, d);<br/>
newDate.addMonths( months );<br/>
<br/>
alert( newDate.getDate() + '.' + newDate.getMonth() + '.' + newDate.getFullYear() );<br/>
Answer the question
In order to leave comments, you need to log in
var date = new Date('08/31/2011');
var N = 1;
date.setMonth(date.getMonth() + N);
date.setDate(0);
alert(date);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question