How to add months to a date in JavaScript?

ID : 10163

viewed : 23

Tags : javascriptdatejavascript

Top 5 Answer for How to add months to a date in JavaScript?

vote vote

100

Corrected as of 25.06.2019:

var newDate = new Date(date.setMonth(date.getMonth()+8)); 

Old From here:

var jan312009 = new Date(2009, 0, 31); var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8); 
vote vote

80

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.

vote vote

74

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"

vote vote

60

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!

vote vote

50

<!DOCTYPE html>  <html>      <head>          <title>Test</title>          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />          <script type="text/javascript">          function codeAddress() {              alert('ok');          }          window.onload = codeAddress;          </script>      </head>      <body>            </body>  </html>

Top 3 video Explaining How to add months to a date in JavaScript?

Related QUESTION?