This question already has an answer here:
-
JavaScript function to add X months to a date
17 answers
I want to add months to a date in JavaScript.
For example: I am inserting date 06/01/2011
(format mm/dd/yyyy
) and now I want to add 8 months to this date. I want the result to be 02/01/2012
.
So when adding months, the year may also increase.
From here:
var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009 = jan312009.setMonth(jan312009.getMonth()+8);
Split your date into year, month, and day components then use Date:
var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);
Date will take care of fixing the year.
I took a look at the datejs and stripped out the code necessary to add months to a date handling edge cases (leap year, shorter months, etc):
Date.isLeapYear = function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
};
Date.getDaysInMonth = function (year, month) {
return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};
Date.prototype.isLeapYear = function () {
return Date.isLeapYear(this.getFullYear());
};
Date.prototype.getDaysInMonth = function () {
return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};
Date.prototype.addMonths = function (value) {
var n = this.getDate();
this.setDate(1);
this.setMonth(this.getMonth() + value);
this.setDate(Math.min(n, this.getDaysInMonth()));
return this;
};
This will add "addMonths()" function to any javascript date object that should handle edge cases. Thanks to Coolite Inc!
Use:
var myDate = new Date("01/31/2012");
var result1 = myDate.addMonths(1);
var myDate2 = new Date("01/31/2011");
var result2 = myDate2.addMonths(1);
->> newDate.addMonths -> mydate.addMonths
result1 = "Feb 29 2012"
result2 = "Feb 28 2011"
I would highly recommend taking a look at datejs. With it's api, it becomes drop dead simple to add a month (and lots of other date functionality):
var one_month_from_your_date = your_date_object.add(1).month();
What's nice about datejs
is that it handles edge cases, because technically you can do this using the native Date
object and it's attached methods. But you end up pulling your hair out over edge cases, which datejs
has taken care of for you.
Plus it's open source!