Javascript date getYear () returns a different result between IE and Firefox, how to approach this?

Apparently, the javascript getYear () date object method returns a different result between IE8 and Firefox3.6 (I have these 2 on my machine, not sure about another browser or version)

Date d = new Date(); alert(d.getYear()); FF3.6 ==> 111 (year since 1900? i guess) IE8 ===> 2011 

I tested only Firefox, and now my Javascript code, which adjusts the return value of getYear (), now gives me 3911 due to my encoding.

 var modified = d.getYear() + 1900 

In Firefox, this will return 2011. But if I applied this approach to IE8, it will return 3911.

I could add logic to distinguish between IE and Firefox, but I don't want to add such if / else everywhere in my code wherever there are browser-dependent parts like this. Is there any other way to approach this problem?

 var browserName=navigator.appName; if (browserName=="Netscape") { var modified = d.getYear() + 1900 } else if(browserName=="Microsoft Internet Explorer") { var modified = d.getYear(); } 
+8
javascript date browser-detection
source share
5 answers

Use .getFullYear () instead of .getYear ()

+19
source share

try using getFullYear () instead of getYear

+8
source share

If IE8 gives you 2011, This is a bug in IE8 (and earlier, see the update below). getYear defined in the specification (section B.2.4) as:

  • Let t be the value of time.
  • If t is NaN , return NaN .
  • Return YearFromTime(LocalTime(t)) − 1900 .

So now 111 is the correct value. This definition has not changed since the 3rd edition, so we say ~ 12 years of this behavior.

As others have said, use getFullYear to get a more useful value, but this is an IE8 error if it really is as you said (I don't have IE8 to check) .


Update : Well, I will. Just tried it, and Microsoft did it wrong. IE6, IE7, and IE8 say 2011. The good news is that they finally fixed it, IE9 says “111” as it should. You can try it in your browser here: http://jsbin.com/ofuyi3

+4
source share

Do not rely on product versions when you do not need it. Instead, rely on the difference you want to fix. If you want getYear correct value, you can get it with

 Date d = new Date(); var year = d.getYear(); if (year < 1900) { // Should always be true, but isn't in older IE. year += 1900; } 

I understand that people have suggested a better way to get the result, but I thought the actual question was worth answering.

+4
source share

Use date.getFullYear ();

blah .. must answer at least 30 characters ...

+2
source share

All Articles