vegad
vegad

Reputation: 23

How To add number of month into the given date in javascript?

I want to add month into the select date by the user.

startdate=document.getElementById("jscal_field_coverstartdate").value;

now I want to add 11 month from the above startdate. How to do that.

date format = 2013-12-01

Upvotes: 0

Views: 149

Answers (4)

Samene
Samene

Reputation: 29

Try this:

baseDate.setMonth(2);    
baseDate.setDate(30);
noMonths = 11;
var sum = new Date(new Date(baseDate.getTime()).setMonth(baseDate.getMonth() + noMonths);
if (sum.getDate() < baseDate.getDate()) {  sum.setDate(0);  }
var m = newDate.getDate();
var d =  newDate.getMonth() + 1;
var yyyy = newDate.getFullYear();
return (yyyy+"-"+m+"-"+d);

Notes:

Adding months (like adding one month to January 31st) can overflow the days field and cause the month to increment (in this case you get a date in March). If you want to add months and then overflow the date then .setMonth(base_date.getMonth()+noMonths) works but that's rarely what people think of when they talk about incrementing months. It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.

Upvotes: 0

Praveen
Praveen

Reputation: 56509

Without the date format it is difficult to tell, however you can try like this

add11Months = function (date) {
    var splitDate = date.split("-");
    var newDate = new Date(splitDate[0], splitDate[1] - 1, splitDate[2]);
    newDate.setMonth(newDate.getMonth() + 11);
    splitDate[2] = newDate.getDate();
    splitDate[1] = newDate.getMonth() + 1;
    splitDate[0] = newDate.getFullYear();
    return startdate = splitDate.join("-");
}

var startdate = add11Months("2013-12-01");
alert(startdate)

JSFiddle

Upvotes: 2

Ankit Zalani
Ankit Zalani

Reputation: 3168

You can do it like this:

var noOfMonths = 11
var startdate = document.getElementById("jscal_field_coverstartdate").value;
startdate.setMonth(startdate.getMonth() + noOfMonths)

Upvotes: 0

AGupta
AGupta

Reputation: 5734

If your startdate is in correct date format you can try using moment.js or Date object in javascript.
In Javascript, it can be achieved as follow:

var date = new Date("2013-12-01");
console.log(date);  
//output: Sun Dec 01 2013 05:30:00 GMT+0530 (India Standard Time)
var newdate = date.setDate(date.getDate()+(11*30));  
console.log(new Date(newdate));  
// output: Mon Oct 27 2014 05:30:00 GMT+0530 (India Standard Time)  

In above lines, I have used 30 days per month as default. So you will get exact 11 month but little deviation in date. Is this what you want ? You can play around this likewise. I hope it help :)
For more about Date you can visit to MDN.

Upvotes: 1

Related Questions