admin管理员组

文章数量:1243219

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!

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!

Share Improve this question asked Feb 25, 2010 at 21:09 RioRio 14.9k22 gold badges71 silver badges109 bronze badges 4
  • Why is newyear only 5 days after now? – kennytm Commented Feb 25, 2010 at 21:13
  • Oddly, works in IE 7, yielding "2010". Haven't bothered to test in other browsers. – jball Commented Feb 25, 2010 at 21:15
  • @jball: Yeah. IE is always the one that stands out. – kennytm Commented Feb 25, 2010 at 21:17
  • A little testing shows that IE treats both getYear() and getFullYear() identically. More reasons not to use deprecated functions. – jball Commented Feb 25, 2010 at 21:22
Add a ment  | 

3 Answers 3

Reset to default 15
(new Date()).getYear()

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

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

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()

本文标签: datetimeAdding dates in JavaScript in one lineStack Overflow