JavaScript Date.getYear()传回111

JavaScript Date.getYear()传回111

接获使用者回报,某个透过JavaScript取日期的网页在某些机器上产生的年份有误,得到"111"的诡异结果!

追踪程式,发现它是用new Date().getYear()方法取年,而不是大家惯用的getFullYear()。而我们也很幸运地在一台Windows 7 + IE9完成问题重现,getYear()得到111,getFullYear()得到2011:

有趣的是,此时找了另一台Win7 + IE9测试getYear()还真的传回2011,顺利地证实"有些IE9正常取得2011,有些IE9却传回111"的现象确实存在。

爬文找到MDN getYear()文件,才发现是自已孤陋寡闻:

  1. getYear()原本用来传回两位数的年份,想当然尔肯定有Y2K问题,故早已不再建议使用。(是谁写进程式里的,踹供!)
  2. 为了向前相容,至今getYear()仍然继续可用,针对超过2000的年份,会传回getFullYear() - 1900,所以2011 - 1900 = 111,这就是111的由来。
  3. 如果是1900以前,则传回负数,例如: 1895 - 1900 = -5。

换句话说,依此原则传回111才是对的,传回2011反而是错的(跟原本认知相反)。而看完Mozilla官方文件,我心中对于"同是IE9,行为却不同"也有了答案。推测是努力向HTML业界标准看齐的IE,终于从IE9起洗心革面改掉getYear()行为,以求与众家浏览器一致!

把IE9的文件模式改成IE8再试一次,果然就传回2011(如下图),证实我的推论: 之所以在不同IE9上得到不同结果,乃源于文件模式不同,在IE9+标准文件模式下,getYear()才会得到111;当IE9开启相容模式(或使用IE7, IE8)时,则会得到2011

最后补充MSDN文件作为呈堂证供: (很有趣的一点,远古时代的IE3跟IE9的行为是一致的,都是getFullYear() - 1900;而IE4到IE8,则是1900至1999传回两位数,范围之外传回四位数)

In Internet Explorer 3.0, and then in Internet Explorer versions starting with Internet Explorer 9 standards mode, the value returned is the stored year minus 1900. For example, the year 1899 is returned as -1 and the year 2000 is returned as 100.

In Internet Explorer 4.0 through Internet Explorer 8 standards mode, the formula depends on the year. For the years 1900 through 1999, the value returned is a 2-digit value that is the stored year minus 1900. For dates outside that range, the 4-digit year is returned. For example, 1996 is returned as 96, but 1825 and 2025 are returned as is.

另外的结论是: 将来谁再敢写.getYear(),一律阿鲁巴伺侯!!

欢迎推文分享:
Published 13 December 2011 06:11 PM 由 Jeffrey
发布了25 篇原创文章 · 获赞 12 · 访问量 25万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章