Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding 1 Year to a Date with JavaScript

Tags:

javascript

I have the following date:

2014-10-29

I am trying to add one year to the date (not 365 days, but 1 year):

var newDate = new Date('2014-10-29');

newDate.setDate(newDate.getFullYear() + 1);

var yyyy = newDate.getFullYear().toString();
var mm = (newDate.getMonth() + 1).toString();
var dd = newDate.getDate().toString();

var mmChars = mm.split('');
var ddChars = dd.split('');
var newClosingDate = yyyy + '-' + (mmChars[1] ? mm : "0" + mmChars[0]) + '-' + (ddChars[1] ? dd : "0" + ddChars[0]);

This returns 2020-04-06, which is obviously wrong.

What am I doing wrong here?

like image 558
user979331 Avatar asked Nov 25 '15 18:11

user979331


People also ask

How is declare the year in JavaScript?

To get the current year, use the getFullYear() JavaScript method. JavaScript date getFullYear() method returns the year of the specified date according to local time. The value returned by getFullYear() is an absolute number.

Can you add dates in JavaScript?

You can simply use the setDate() method to add number of days to current date using JavaScript. Also note that, if the day value is outside of the range of date values for the month, setDate() will update the Date object accordingly (e.g. if you set 32 for August it becomes September 01).


1 Answers

var date = new Date("2014-10-29"); 
date.setFullYear(date.getFullYear() + 1);
like image 60
Travis Clarke Avatar answered Sep 22 '22 00:09

Travis Clarke