Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Javascript getYear() return 108?

Why does this javascript return 108 instead of 2008? it gets the day and month correct but not the year?

myDate = new Date(); year = myDate.getYear(); 

year = 108?

like image 351
ctrlShiftBryan Avatar asked Sep 18 '08 23:09

ctrlShiftBryan


2 Answers

It's a Y2K thing, only the years since 1900 are counted.

There are potential compatibility issues now that getYear() has been deprecated in favour of getFullYear() - from quirksmode:

To make the matter even more complex, date.getYear() is deprecated nowadays and you should use date.getFullYear(), which, in turn, is not supported by the older browsers. If it works, however, it should always give the full year, ie. 2000 instead of 100.

Your browser gives the following years with these two methods:

* The year according to getYear(): 108 * The year according to getFullYear(): 2008 

There are also implementation differences between Internet Explorer and Firefox, as IE's implementation of getYear() was changed to behave like getFullYear() - from IBM:

Per the ECMAScript specification, getYear returns the year minus 1900, originally meant to return "98" for 1998. getYear was deprecated in ECMAScript Version 3 and replaced with getFullYear().

Internet Explorer changed getYear() to work like getFullYear() and make it Y2k-compliant, while Mozilla kept the standard behavior.

like image 137
ConroyP Avatar answered Sep 23 '22 03:09

ConroyP


Since getFullYear doesn't work in older browsers, you can use something like this:

Date.prototype.getRealYear = function()  {      if(this.getFullYear)         return this.getFullYear();     else         return this.getYear() + 1900;  }; 

Javascript prototype can be used to extend existing objects, much like C# extension methods. Now, we can just do this;

var myDate = new Date(); myDate.getRealYear(); // Outputs 2008 
like image 28
FlySwat Avatar answered Sep 24 '22 03:09

FlySwat