1

I am pretty new in JavaScript and I have the following problem.

I have to retrieve the actual year (that is 2015).

So I done in this way:

var oggi = new Date();
var year = oggi.getYear();

The problem is that the value of year variable is 115, I think that it depend by the fact that it is calculated started by 1900, infact 1900 + 115 = 2015

I know that I can add the 1900 value to the value retrieved into the year variable so I will obtain the desidered actual year value. But it seems to me a dirty solution. Can I do the same thing with a better solution?

Tnx

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • `getYear()` is deprecated precisely because of the behaviour you have identified. Use `getFullYear()` instead. –  May 06 '15 at 14:29

2 Answers2

4

Use getFullYear() to return a four-digit year:

var oggi = new Date();
var year = oggi.getFullYear();

In fact, the getYear() method is deprecated and, as described, returns 0 for any year less than 1900.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
3

Per the MDN docs, getYear does in fact return the current year - 1900. That's the documented behavior, shown in the spec at B.2.4, so what you're doing is completely safe and reasonable. However...

The getYear method has been deprecated and replaced with getFullYear, which returns a full four-digit year and is the preferred method now. getFullYear was defined in ES5.1, section B.2.4. Per the MSDN docs, full year looks like it was supported as far back as IE6 (compatibility table).

ssube
  • 47,010
  • 7
  • 103
  • 140