HTML5, CSS3, jQuery, JSON, Responsive Design...

Avoid using JavaScript getYear() function

Michael Brown   June 21 2010 04:09:19 AM
This is is what happens when you design for a monoculture - especially one as godawful as Microsoft's - instead of designing to standards.

The JavaScript function getYear() is supposed to return the year from a date value, but relative to the year 1900.  So, if you ran the code below:

var todayVar = new Date; // Initialised to today's date

on today's date, 21st June 2010, it should return the number "110".  And on any browser other than IE, that's exactly what it does.  IE on the other hand, returns the full, four-digit year, "2010"; that's on all versions of IE, up to and including version 8.

Why is this a problem?  Well, it's not if all you're ever planning to use is IE.  And if that describes you, then you seriously need shooting.  The problem occurs, of course, if you use any browser other than IE.  For example, I've just seen an application that relied on getYear() returning a four-digit date to do its thing.  The developer had seen getYear() do that in IE and simply assumed that's what the function is supposed to do rather than looking the function up.  The end result was that IE appeared to be the only browser that worked correctly, whereas other browsers produced screwy results.

If that developer had tested with just one other browser, he'd have spotted his mistake and rectified it.  The correct function to use, by the way, is getFullYear(), which returns a four-digit year on any browser.  


1Petter  06/21/2010 6:26:08 AM  Avoid using JavaScript getYear() function

Use getFullYear()

2Mike Brown  06/21/2010 6:45:51 AM  Avoid using JavaScript getYear() function

Yes, Petter.

And I said so in the last line of the post!

3Petter  06/21/2010 7:10:05 AM  Avoid using JavaScript getYear() function

Sorry Mike..

n2s: read entire blog entry :-)

4Rohan  11/16/2010 9:49:20 PM  Avoid using JavaScript getYear() function

Please use the getFullYear() method i have fallern in the same pit fall , since safair and opera,crmome does not treate the year (2010) , so use of the getFulYear() will every time be consistant across the browsers.