Mozilla Firefox 对函数 getYear() 返回不正确的原因和解决办法

先看一段JS代码


这段代码在Microsoft Internet Explorer中执行正常,输出2005年10月14日星期五,但在Mozilla Firefox浏览器中却显示为105年10月14日星期五,这个问题在其它许多网站上都存在,我觉得问题的关键在于:浏览器对于JS代码解释的差异性。

IE中:
today=new Date();
today.getYear()返回的是绝对的公元纪年,2005

Firefox中:
today=new Date();
today.getYear()返回的是相对绝对的年份,年份相对于1900,因为今年是2005,两者相减是105。

这个问题的根源在于2000年问题,以前年份的表示使用2位数字,在ECMAScript Language Specification的规范中是这么描述的Date对象的:

引用内容 引用内容
Date.prototype.getYear ( )

NOTE
The getFullYear method is preferred for nearly all purposes, because it avoids the "year 2000 problem."
When the getYear method is called with no arguments the following steps are taken:
1. Let t be this time value.
2. If t is NaN, return NaN.
3. Return YearFromTime(LocalTime(t)) − 1900.


因此,为了最大范围的兼容性,使用getFullYear() 是正确的,在不同浏览器中都能正确计算。
[本日志由 parno 于 2012-04-20 05:23 AM 更新]
上一篇: ASP 中的数据库访问技术
下一篇: iframe 大小自动适应内容的脚本
文章来自: jhsea3do
引用通告: 查看所有引用 | 我要引用此文章
Tags: Dreamwear 网络 javascript PHP 网页 Web HTML IE Firefox DHTML
相关日志:
评论: 0 | 引用: 0 | 查看次数: 9974