js中getYear()在不同浏览器中的兼容性及解决方案

  • 二月 22nd, 2010

在调试程序时,客户有要求页首需要增加时间显示。显然就用到了Date()中的getYear()来直接显示年份:

var now  = new Date();
var year = now.getYear();
document.write(year);

IE显示正常,但在firefox和chrome下显示为110年(应该显示为1900+110=2010年),在网上搜索了一下答案,得到结论是IE为了提高兼容性,只要通过Date()取得的年份是两位或三位,那么就认为人的寿命不可能是1900年之多,所以智能的自动增加1900作为显示结果,即用getYear()即可显示为2010。但对于firefox和chrome等遵循标准的浏览器来讲,这样的做法显然有些可笑,于是搜索到这个解决办法:

var now  = new Date();
var year = ( now.getYear() < 1900 ) ? ( 1900 + now.getYear() ) : now.getYear();
document.write(year);

上面的解决办法是对年份进行判断,小于1900则自动加上以显示正确年份,这样就完全兼容了所有浏览器的年份显示。

其实这里要写的不只是上面的解决方案,最佳解决方案是这样的:getYear()是js1.0标准的旧用法,现在提倡用getFullYear()即可得到完整年份:

var now  = new Date();
var year = now.getFullYear();
document.write(year);

to “js中getYear()在不同浏览器中的兼容性及解决方案”

给我回复