views:

169

answers:

3

Hi everyone, I'm trying to perform date manipulations using JavaScript on a single line, and I'm having problems with the year (not the month or day). I got the idea from this link. Am I missing something?

The code is as follows:

var newyear = new Date((new Date()).getYear(), (new Date()).getMonth(), (new Date()).getDate()+5).getFullYear();
document.write(newyear);

This gives me "110".

I'm not sure why? Thanks!

+6  A: 
KennyTM
Thank you. That helped.
Rio
A: 
var newyear = new Date((new Date()).getFullYear(), (new Date()).getMonth(), (new Date()).getDate()+5).getFullYear();
zincorp
A: 

Y2K bug aside, this is a simpler expression:

var newyear = new Date(new Date().setDate(new Date().getDate()+5)).getFullYear()

Date objects are relatively expensive and you can do this with a single Date object and less code if you don't assume it has to be a single expression.

var d = new Date(); d.setDate(d.getDate()+5); var newyear = d.getFullYear()
peller