【问题标题】:NodeJS incorrect `console.log` Date valueNodeJS不正确的`console.log`日期值
【发布时间】:2020-04-04 10:30:25
【问题描述】:

NodeJS 在console.log 中输出不正确的日期值

假设: var todayDate = new Date();

机器时区:GMT+0530 / IST

以下是结果:

#1

console.log ('Today date:', todayDate);

输出: 020-04-04T09:54:29.107Z

#2 console.log ('Today date as UTC:', todayDate.toUTCString());

输出:今天的 UTC 日期:2020 年 4 月 4 日星期六 09:54:29 GMT

#3 console.log ('Today date as string:', todayDate.toString());

输出:今天日期为字符串:Sat Apr 04 2020 15:24:29 GMT+0530(印度标准时间)

我得到的是输出#1,而预期的输出是#3。

Chrome 浏览器显示的结果与我对 NodeJS 的预期结果相同,因为它在 Chrome 引擎上运行。

请解释为什么 NodeJS 不以本地日期/时间输出。

【问题讨论】:

  • 你得到了什么输出而不是预期的输出?我在节点(v12)和我的 chrome 浏览器中得到完全相同的输出,即Sat Apr 04 2020 12:45:57 GMT+0200 (Central European Summer Time) 在我的例子中。
  • 我得到的是输出#1,而预期的输出是#3。
  • 啊现在我明白了 - 有趣,不知道。似乎默认格式化程序在实现中有所不同。

标签: node.js


【解决方案1】:

从根本上说,Date 对象在 chrome 和 node 中是相同的。它包含自 UNIX 纪元以来经过的秒数。然而,不同的平台选择以不同的方式显示它。 Node.js 调用 toISOString(),而 Chorome 调用 toString()(Node.js 中的toString() 将返回与 Chrome 中相同的结果)。

【讨论】:

  • 请提供参考以支持您的回答。 NodeJS 文档中提到过吗?
  • 我认为在任何地方都没有提到它。在代码库github.com/nodejs/node/blob/… 中,如果 Date.getTime() 为 NaN,您可以看到它使用 Date.toString() 格式化,否则使用 Date.toISOString() 格式化。稍微玩弄一下代码,显然 Date.toISOString() 在时间为 NaN 时抛出错误,并且 toString() 在 V8 中返回 'Inavlid Date'。
  • 你可以实际尝试一下 (new Date(undefined)).toISOString() -> Error and (new Date(undefined)).toString() -> 'Invalid Date'。 new Date(undefined) 打印“Invalid Date”,因此它是用 toString() 格式化的。因此,根据代码库,如果时间为 NaN,则使用 toString() 格式化,否则使用 toISOString() 格式化。
  • 这是我一直在寻找的答案,在 docker 中设置 TZ 并确认它在图像中很好......我对所有自定义设置的 UTC 来自哪里感到非常困惑。 ty
  • 顺便说一句,我用This work around with Morgan
【解决方案2】:

我可以确认这种行为。就我而言,我正在从数据库中循环遍历 unix 日期:

    console.log(endunix); //epoch date
    console.log(endutc); // wrong date that will be fixed from unixdate
    let nowadatautc = new Date(endunix*1000);
    console.log(nowadatautc); // new date
let sql2 = "update schedule a set end_time_utc='"+nowadatautc+"' where a.`event_id` > 374 and a.`sport_id` = 5";

我得到:

1645328100
2022-02-20T03:05:00.000Z
2022-02-20T03:35:00.000Z
update schedule a set end_time_utc='Sun Feb 20 2022 04:35:00 GMT+0100 (czas środkowoeuropejski standardowy)' where a.`event_id` > 374 and a.`sport_id` = 5

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2017-11-02
    • 2020-06-17
    相关资源
    最近更新 更多