首页 > 解决方案 > javascript中的 Date(d.getTime()) 和 new Date(d.getTime()) 有什么区别?

问题描述

我一直在处理日期并意识到这两个命令Date(d.getTime())new Date(d.getTime())不同的。

当我运行这个片段时:

        var d = new Date(2016,11,12);
        console.log(Date(d.getTime()));
        console.log(new Date(d.getTime()));

我有这个结果:

(index):68 Thu Dec 12 2019 18:02:41 GMT-0300 (Horário Padrão de Brasília)
(index):69 Mon Dec 12 2016 00:00:00 GMT-0200 (Horário de Verão de Brasília)

为什么它们不同?

我试图找到一些答案,但我没有找到。这些是我经历过的一些参考资料:

Date(dateString) 和 new Date(dateString) 之间的区别

为什么我们不能在没有 new 运算符的情况下调用 Date() 类的方法

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.2

标签: javascriptdate

解决方案


Date获取window/globalDate对象,new Date()创建一个新的静态Date对象。当您创建一个时,new Date()您会及时冻结它的价值。

使用时Date(),它会返回当前日期的字符串表示形式,就像调用new Date().toString().

根据您的代码:

// this is a new date, Dec. 12, 2016
var d = new Date(2016,11,12);  

// this returns the time value of Date d
d.getTime()

// Calling Date as a function just returns a string for
// the current date, arguments are ignored
console.log(Date(d.getTime())); 

// this creates a new date based on d's time value
console.log(new Date(d.getTime()));

推荐阅读