new Date() 与 Date() 为什么 return 不同的时间(-2 小时)?

new Date() vs Date() and why does it return a different time (-2 hours)?

我有这 2 个控制台日志,但它们 return 不同的时间(-2 小时)。

console.log(new Date()) // Date 2015-04-20T15:37:23.000Z
console.log(Date()) // "Mon Apr 20 2015 17:37:23 GMT+0200 (CEST)"

我知道使用 Data() 与使用构造函数并调用 .toString() 是一样的。

但是,我确实需要 Date() 时间而不是新的 Date() 时间。那么,为什么 return 设置了错误的时间,我该如何重置它以输出正确的时间?

谢谢,

那些是同一时间。 Date()生成的字符串只是使用了不同的时区,从GMT+0200 (CEST)后缀可以看出。

因此,如果您需要本地时区的时间字符串,只需使用 .toString() 而不是 .toUTCString()

So why is it returning the wrong time and how can i reset it to output the correct one?

您的第一条语句是使用 Date 对象调用 console.log。看起来无论您使用的是什么 browser/console 插件,都会选择使用 UTC 中的 ISO-8601 字符串来显示 Date 对象。例如,格式由 console 实现选择。

您的第二条语句是使用 字符串 调用 console.log,因此格式由 Date 实现选择。 specification makes no requirement on what that string format must be 从 JavaScript 引擎到 JavaScript 引擎(是的,真的*)除此之外它必须在当地时区。

显然,在您的浏览器上,console 实现和 Date#toString 实现不匹配。

However, i do need the Date() time and not the new Date() time.

这些字符串定义了同一时刻(前后几微秒);只是字符串是用不同的时区设置准备的。

如果您需要在本地时间将 字符串 记录到控制台,请使用

console.log(String(new Date()));

...从 Date 对象可靠地获取字符串,而不是由 console.

生成的字符串

* 是的,您从 Date#toString 获得的格式是未定义的,完全取决于 JavaScript 实现;唯一的要求是 Date()Date.parse() 都可以解析字符串 toString 输出并返回到原始日期。 (JavaScript 甚至没有标准的 date/time 格式 until ES5, and it only applies to the toISOString method, not toString. And ES5 got it slightly wrong and it had to be amended in ES6,导致目前不幸的情况是 Chrome 在解析字符串时做一件事而 Firefox 做另一件事没有时区的新 date/time 格式。)