接獲使用者回報,某個透過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(),一律阿魯巴伺侯!!


Comments

# by 91

大推:『將來誰再敢寫.getYear(),一律阿魯巴伺侯!!』

# by Alex Lee

萬一programmer 是女性同胞?

# by ADF

一樣阿魯巴伺侯 但柱子換成我

# by KK

如果是又肥又醜呢?

# by ??

一樣阿魯巴伺侯 但柱子換成你

Post a comment