我自己做了更多的调查并得出了这样的结论:这是不可能的壮举,由于 Date 类的实现方式。
我已经检查过蜘蛛猴 http://www.mozilla.org/js/spidermonkey/源代码以查看日期是如何实现的。我认为这一切都可以归结为以下几行:
static JSBool
Date(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval)
{
jsdouble *date;
JSString *str;
jsdouble d;
/* Date called as function. */
if (!(cx->fp->flags & JSFRAME_CONSTRUCTING)) {
int64 us, ms, us2ms;
jsdouble msec_time;
/* NSPR 2.0 docs say 'We do not support PRMJ_NowMS and PRMJ_NowS',
* so compute ms from PRMJ_Now.
*/
us = PRMJ_Now();
JSLL_UI2L(us2ms, PRMJ_USEC_PER_MSEC);
JSLL_DIV(ms, us, us2ms);
JSLL_L2D(msec_time, ms);
return date_format(cx, msec_time, FORMATSPEC_FULL, rval);
}
/* Date called as constructor. */
// ... (from here on it checks the arg count to decide how to create the date)
当 Date 用作函数时(或者作为Date()
or Date.prototype.constructor()
,它们是完全相同的),它默认以区域设置格式的字符串形式返回当前时间。这与传入的任何参数无关:
alert(Date()); // Returns "Thu Oct 09 2008 23:15:54 ..."
alert(typeof Date()); // Returns "string"
alert(Date(42)); // Same thing, "Thu Oct 09 2008 23:15:54 ..."
alert(Date(2008, 10, 10)); // Ditto
alert(Date(null)); // Just doesn't care
我不认为在 JS 级别可以做任何事情来规避这个问题。而这大概就是我对这个话题的追求的结束了。
我还注意到一些有趣的事情:
/* Set the value of the Date.prototype date to NaN */
proto_date = date_constructor(cx, proto);
if (!proto_date)
return NULL;
*proto_date = *cx->runtime->jsNaN;
Date.prototype
是一个 Date 实例,其内部值为NaN
因此,
alert(Date.prototype); // Always returns "Invalid Date"
// on Firefox, Opera, Safari, Chrome
// but not Internet Explorer
IE没有让我们失望。它的做法有点不同,可能将内部值设置为-1
这样 Date.prototype 总是返回一个稍早于纪元的日期。
Update
我终于深入研究了 ECMA-262 本身,事实证明,我想要实现的(使用 Date 对象)——根据定义——是不可能的:
15.9.2 作为函数调用的日期构造函数
当 Date 被称为
函数而不是构造函数,
它返回一个表示
当前时间 (UTC)。
NOTE功能
称呼Date(…)
不等于
对象创建表达式new Date(…)
具有相同的论点。
15.9.2.1 日期 ([ 年 [ 月 [ 日期 [ 小时 [ 分钟 [ 秒 [
多发性硬化症 ] ] ] ] ] ] ] )
全部
参数是可选的;任何论据
所提供的已被接受,但
完全被忽略了。一个字符串是
创建并返回,就像由
表达(new Date()).toString()
.