【问题标题】:What is the difference between Date(d.getTime()) and new Date(d.getTime()) in javascript? [duplicate]javascript中的 Date(d.getTime()) 和 new Date(d.getTime()) 有什么区别? [复制]
【发布时间】:2019-12-12 21:06:13
【问题描述】:

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

当我运行这个 sn-p 时:

        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)

它们为什么不同?

我试图找到一些答案,但没有找到。以下是我看过的一些参考资料:

Difference between Date(dateString) and new Date(dateString)

Why we can't call methods of Date() class without new operator

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

【问题讨论】:

  • 您问题中的第一个链接如何不直接回答您的问题?这看起来应该作为该问题的副本关闭....第二个问题怎么不是重复的?
  • 我知道一个函数是一个与对象方法不同的函数。但是为什么工作日不一样呢?
  • 为什么不会他们是不同的?什么不清楚?
  • 不完全,还有工作日的问题。
  • 因为2019年和2016年是不同的年份?

标签: javascript date


【解决方案1】:

Date 获取window/global Date 对象,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()));

【讨论】:

    【解决方案2】:

    【讨论】:

    • 好的,但是为什么他们的工作日不同?
    • @DiogoBratti 阅读了“代表当前日期而与传递给它的参数无关”的部分。
    • 好的,但为什么 12 月 12 日是周一和周四?
    • @DiogoBratti 你认为每年 12 月 12 日是同一天吗?
    • @DiogoBratti 不是吗? 2016 年不是 2019 年。
    猜你喜欢
    • 2014-11-26
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 2019-11-12
    相关资源
    最近更新 更多