1

I am trying to add months to a given date and want to output that date.

I am using this code, but it is not working.

    var p = '2015-10-21';
    var myDate = new Date(p);
    var result1 = myDate.addMonths(3);

I want the result to be: 2016-01-21

John Hascall
  • 9,176
  • 6
  • 48
  • 72
Handoet1928
  • 63
  • 1
  • 5

3 Answers3

1

You want to getMonth/setMonth

var p = '2015-10-21';
var myDate = new Date(p);
myDate.setMonth(myDate.getMonth() + 3);

Don't worry about overflow - Date object handles it

Note. This overwrites myDate, if you want the result in a different var

var p = '2015-10-21';
var myDate = new Date(p);
var result1 = new Date(myDate);
result1.setMonth(result1.getMonth() + 3);

as noted by @JohnHascall in the comments, this isn't fool proof around the end of month, for example adding three months to 30 November 2015 will result in 1st March 2016

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • Be careful around the end of months. For example: adding 3 months to the last day of November gives March 1st -- which may or may not be what you are expecting. – John Hascall Jan 09 '16 at 06:09
  • @JohnHascall Good point - I'll add that warning to the answer for completeness - does any library handle such cases, and what SHOULD be the result in such cases (guess that's a matter of opinion) – Jaromanda X Jan 09 '16 at 06:11
  • I think most date libraries would adjust that to the last day of the month. But as you say, what is 'right' is a matter of opinion. – John Hascall Jan 09 '16 at 06:15
1

The moment library is awesome for date related functions. You can do operations like add, subtract, etc. It has a syntax which is easily understandable.u can also avoid edge cases

If you included the moment library, your code could be rewritten like this

var p = '2015-10-21';
var myDate = moment(p, 'YYYY-MM-DD');
var result1 = myDate.add(3, 'months');
console.log (result1.format('YYYY-MM-DD'));

You can learn about or download moment from: http://momentjs.com/

sundar
  • 398
  • 2
  • 12
0

You can try this -

<script>
   var date = new Date();
   var month = date.getMonth()+1;
   var year = date.getFullYear();
   var day = date.getDate();

   function addMonth(addMonth){
     var u_date,u_year,u_month;
     u_date = month + addMonth;
     if(u_date > 12){
       var div = Math.floor(u_date / 12);
       var rem = u_date % 12;
       u_year = year + div;
       u_month = month + rem;
       document.getElementById("updated_date").innerHTML = day +" "+  u_month + " " + u_year;
     }else{
        document.getElementById("updated_date").innerHTML = day +" "+ (month+addMonth) + " " + year;
  }
}

addMonth(13);


</script>

Here is the html-

<div id="updated_date"></div>
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30