F
F
Fastto2011-08-27 14:47:19
JavaScript
Fastto, 2011-08-27 14:47:19

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() &lt; d )<br/>
 this.setDate( 0 );<br/>
<br/>
this.setDate( this.getDate()-1 );<br/>
<br/>
};

Basically, the result is correct, but there are also glitches, for example:
I set August 1 of this year + 1 month = August 30 I set August
31 of this year + 1 month = September 31 !!!
example code
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/>

An example in an online sandbox
Question: Are there regular means in JS for NORMAL date manipulation?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mark_ablov, 2011-08-27
@Fastto

var date = new Date('08/31/2011');
var N = 1;
date.setMonth(date.getMonth() + N);
date.setDate(0);
alert(date);

M
Mark, 2011-08-27
@printf

I usually use datejs for things like this .

Date.today().add(1).months();
// или даже так
var n = 1;
n.months().fromNow();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question