【问题标题】:How to save datetime with local time zone in mysql using momentjs如何使用momentjs在mysql中保存本地时区的日期时间
【发布时间】:2019-08-06 08:02:20
【问题描述】:

我读了很多堆栈溢出页面,但我不明白为什么日期时间总是以 UTC 格式保存在 MySQL 数据库中,尽管本地时间是 UTC+2。

我试试

const now = moment().local();

const now = moment(new Date()).local().format("YYYY-MM-DD HH:mm:ss");
console.log(now)    <-- display the right local time (UTC+2)

但是一旦now被发送到数据库,时间就会以UTC格式保存。

为什么?

使用的数据库是 MySQL,@@global.time.zone 设置为 SYSTEM。我的系统已配置为 UTC+2。

【问题讨论】:

    标签: node.js date momentjs locale


    【解决方案1】:

    您应该为此使用moment-timezone

    const moment = require('moment-timezone');
    const date = moment("2019-01-01 14:40:00");
    console.log(date.tz("Asia/Kolkata").format());
    

    【讨论】:

    • 如果我理解得很好,moment-timezone 允许我将日期时间显式转换为任何时区。那么moment().local() 的目标是什么?为什么console.log(now) 可以,但我的数据库中保存的值不一样?
    【解决方案2】:

    我找到了问题的答案。其实问题不在于 Momentjs,而是我使用 Sequelize 将我的数据保存在数据库中。 默认情况下,Sequelize 以 UTC 格式保存所有日期时间格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 2011-06-06
      • 2014-06-23
      • 2019-09-05
      • 2016-03-12
      • 2013-11-19
      • 2017-07-19
      相关资源
      最近更新 更多