Javascript’s getYear() function, and other IE headaches

October 26, 2006

Someone I know came across this gem. I guess it's well publicised, but if you haven't come across it before, it could easily catch you out.

The interesting thing is that IE will give you 2006 for getYear(). That's wrong. It should give 106 (as per http://www.w3schools.com/jsref/jsref_getYear.asp). The correct function to use is getFullYear(). But of course, if you develop for IE primarily, you'll find this and think that other browsers are wrong. Then you'll put stuff in place to detect which browser you're working on, so that the 'buggy' other browsers handle the JavaScript correctly. Then some future version of IE will fix it, and your code will break within IE.

I have come across a menu system a while back that doesn't like IE7 because they had an IE-specific version of their code. Personally, I prefer to write for Firefox first (I find that Firefox has tended in the past to be slightly closer to the W3C standard), and then work on any code that doesn't work properly in IE, so that it displays correctly in both browsers WITHOUT having to have browser-detection. It can be hard, but it's definitely doable. I think it's much safer to stick as close as possible to the standard (but I do appreciate that this is a nice 'theory', and shouldn't be an enforced rule).

Correction: That page gives you the value that the current browser will give. Seems here, Firefox is wrong, as per the description of the function 'it should return 4 digits'. I had browsed to the page which said "this will give you 106", and figured it was correct, when actually, that was a browser quirk. Oh joy!  (Thanks Alun)

Another correction: Seems that JavaScript 1.5 is supposed to give 106, and JavaScript 1.2 and earlier are supposed to give 2006 – http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:Date:getYear – but either way, it's deprecated, and getFullYear() should be used instead.
 

This Post Has 2 Comments

  1. alunj

    The link you quote demonstrates 2006 as being the correct response, and describes that dates before 1900 or after 1999 should produce a four-digit year.
    As you say, though getFullYear is the correct function.
    This arose because the designers of Javascript did not exactly specify the results that getYear should provide past 1999, leading to some browsers returning “06”, others returning “2006”, and some returning “106” – you can see occasional web sites even now telling you that the year is “19106” as a result.

  2. robfarley

    Woah! I had looked at that page in Firefox, where it gives an answer of 106. I guess the source of the code prints it.

    Now that I look at that page in IE, it says 2006. I will correct my post. 😐

    Thanks Alun.

Leave a Reply

LobsterPot Blogs

Blog posts by Rob Farley and other LobsterPot Solutions team members.

Search