【问题标题】:MomentJS keeps defaulting date to GMTMomentJS 保持默认日期为 GMT
【发布时间】:2021-10-19 09:55:41
【问题描述】:

我有

moment(line.dateRange[0], 'DD-MM-YY HH:mm').toDate()

设置,其中输入为字符串:15-10-2021 09:00

Moment 不断输出:2020-10-15T07:00:00.000Z,即使我的 nodeJS 服务器的process.env.TZEurope/Amsterdam

for (const line of orderLines) {
      
    let orderLine = {
            bookingID: bookingDB.id,
            bookingStart: moment(line.dateRange[0], 'DD-MM-YY HH:mm').format(),
            bookingEnd: moment(line.dateRange[1], 'DD-MM-YY HH:mm').format(),
            productID: line.productID,
            type: line.type
         }
         console.log(orderLine)
         lines.push(orderLine);
      }
      const orderLinesDB = await BookingLine.bulkCreate(lines);
      console.log(orderLinesDB)
      res.status(200).send(orderLinesDB);

【问题讨论】:

    标签: node.js express sequelize.js momentjs


    【解决方案1】:

    我怀疑你看到了2020-10-15T07:00:00.000Z 的输出,因为你正在这样做:

    console.log(moment('15-10-2021 09:00', 'DD-MM-YY HH:mm').toDate())
    

    您在输出中看到的是 UTC 时间,这将比欧洲/阿姆斯特丹晚 2 小时,因为 Node.js 在记录日期时会调用 toISOString()。

    尝试拨打moment.format()查看当地时间,使用.toDate().toLocaleString().toDate().toString()

    例如:

    const input = '15-10-2021 09:00';
    
    console.log('UTC time:', moment(input, 'DD-MM-YY HH:mm').toDate())
    console.log('Local time:', moment(input, 'DD-MM-YY HH:mm').format())
    console.log('Local time (II):', moment(input, 'DD-MM-YY HH:mm').toDate().toLocaleString())
    console.log('Local time (III):', moment(input, 'DD-MM-YY HH:mm').toDate().toString())
    

    应该输出

    UTC时间:2020-10-15T07:00:00.000Z 当地时间:2020-10-15T09:00:00+02:00 当地时间(二):15/10/2020, 09:00:00 当地时间(三):Thu Oct 15 2020 09:00:00 GMT+0200(中欧夏令时间)

    这是我们所期望的。

    【讨论】:

    • 是的,第一个选项有效,有点......如果我记录它,那么我将是正确的格式,但是一旦我从 MySQL 检索保存的日期时间,它将再次更改格式
    • 您能否添加一个简短的 sn-p 显示您如何将日期保存到 MySQL,这将有助于诊断那里的任何问题?谢谢!
    • 添加了sn-p,我用的是Sequelize
    • 我相信,一旦您从数据库中读取了日期,例如,同样的问题会以另一种形式表现出来。 bookingStart,你可以尝试做 bookingStart.toString() 或 bookingStart.toLocaleString() 吗?这应该给你当地时间而不是 UTC。
    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多