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!

4
  • Why is newyear only 5 days after now? Commented Feb 25, 2010 at 21:13
  • Oddly, works in IE 7, yielding "2010". Haven't bothered to test in other browsers. Commented Feb 25, 2010 at 21:15
  • @jball: Yeah. IE is always the one that stands out. 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. Commented Feb 25, 2010 at 21:22

3 Answers 3

15
(new Date()).getYear()

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.