【问题标题】:Setting timezone, still getting the wrong date设置时区,仍然得到错误的日期
【发布时间】:2019-02-14 02:13:32
【问题描述】:

您好,我正在使用 node.js 中的 moment 库并设置时区。但是,即使在设置时区之后,当我进行控制台日志记录时,我仍然会得到错误的日期(提前一天)。这是我的示例代码和下面的输出。

代码:

  const moment = require('moment-timezone');
  const log4js = require('log4js');
  let logger = log4js.getLogger();
  logger.level ='debug'
  let date1 = moment().tz("America/New_York").toDate()
  logger.debug(date1)

输出:

  [2019-02-13T21:09:48.019] [DEBUG] default - 2019-02-14T02:09:48.019Z

注意日期比今天的实际日期早一天。

【问题讨论】:

    标签: node.js timezone momentjs


    【解决方案1】:

    它不是随机的,它是 UTC,这是 JavaScript 的原生 Date 处理的(这也是时刻 .toDate 提供的):

    const now = moment();
    const tz1 = 'America/New_York';
    const tz2 = 'Africa/Nairobi';
    
    // false: toDate provides a *copy* of the underlying native Date object
    console.log(now.tz(tz1).toDate() === now.tz(tz2).toDate());
    // true despite not being the same TZ: the underlying native Date is UTC-based
    console.log(now.tz(tz1).toDate().toString() === now.tz(tz2).toDate().toString());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2023-03-10
      • 2012-03-12
      • 1970-01-01
      相关资源
      最近更新 更多