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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With