3

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!

Rio
  • 14,182
  • 21
  • 67
  • 107

3 Answers3

15
(new Date()).getYear()

You should use getFullYear() here. getYear() in JS means (year − 1900).

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
1
var newyear = new Date((new Date()).getFullYear(), (new Date()).getMonth(), (new Date()).getDate()+5).getFullYear();
zincorp
  • 3,284
  • 1
  • 15
  • 18
0

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
  • 4,435
  • 19
  • 21