How to determine one year from now in Javascript

I'm trying to get one year from now's date, and it's not working.

JS:

var now = new Date();

var oneYr = new Date();
oneYr.setYear(now.getYear() + 1);
$("#yearFromNow").append(oneYr.toString());

var oneMonth = new Date();
oneMonth.setMonth(now.getMonth() + 1);
$("#monthFromNow").append(oneMonth.toString());

Output:

one mo. = Thu Dec 22 112 15:16:01 GMT-0500 (Eastern Standard Time)

one yr. = Sun Jan 22 2012 15:16:01 GMT-0500 (Eastern Standard Time)

The year has Dec 22 112 - ?? The month is correctly displaying Jan 22 2012.

If you want to tinker with it, http://jsbin.com/alezaj/edit#javascript,html,live. This is in Chrome and Firefox.

Thanks!


This will create a Date exactly one year in the future with just one line. First we get the fullYear from a new Date, increment it, set that as the year of a new Date. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date object so we wrap the whole thing in a Date constructor.

new Date(new Date().setFullYear(new Date().getFullYear() + 1))

You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).

Thus a date marking exactly one year from the present moment would be:

var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);

Note that the date will be adjusted if you do that on February 29.

Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().


As setYear() is deprecated, correct variant is:

// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)

All examples return Unix timestamp, if you want to get Date object - just wrap it with another new Date(...)


Use this:

var startDate = new Date();
    startDate.setFullYear(startDate.getFullYear() - 1);