【问题标题】:new Date in the context of a string doesn't work in Firefox字符串上下文中的新日期在 Firefox 中不起作用
【发布时间】:2012-03-23 07:56:27
【问题描述】:

以下代码中的最后一次登录在 Firefox 中不起作用。为什么?

(function() {

    String.prototype.toDate = function() {
        return new Date(this);
    };

    console.log(Date.parse("2012-01-31"));
    console.log(new Date("2012-01-31"));
    console.log("2012-01-31".toDate());

})();

为了在浏览器中进行测试,我将上面的 sn-p 放入一个文件并使用以下 HTML。

<!DOCTYPE html>
<body>
    <script src="wtf.js"></script>
</body>

NodeJS (v0.4.12):

1327932000000
Mon, 30 Jan 2012 14:00:00 GMT 
Mon, 30 Jan 2012 14:00:00 GMT

Chrome (17.0.963.79):

1327968000000
Tue Jan 31 2012 10:00:00 GMT+1000 (EST)
Tue Jan 31 2012 10:00:00 GMT+1000 (EST)

火狐(10.0):

1327968000000
Date {Tue Jan 31 2012 10:00:00 GMT+1000 (EST)}
Date {Invalid Date}

【问题讨论】:

    标签: javascript firefox node.js google-chrome


    【解决方案1】:

    this 在 Firefox 的 String.prototype 中似乎没有将字符串作为字符串引用。如果你添加到你的方法中:

    String.prototype.toDate = function() {
            return new Date(String(this));
        };
    

    一切正常。

    【讨论】:

    • 有趣。 new String(this) 不起作用,但 String(this) 和 this.toString() 起作用。
    • 你应该也可以使用('2012-01-31').toDate(),但我现在无法测试。
    猜你喜欢
    • 2013-04-30
    • 2017-10-08
    • 2016-09-15
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多