Sequelize createdAt和updatedAt时间戳是错误的

时间:2018-04-27 07:49:15

标签: timezone timestamp sequelize.js momentjs sequelize-cli

我使用sequelize创建了一个带时间戳的表。当我更新表时,它会自动更新时间戳(即createdAt和updatedAt)。但这些时间与我当地时间不同。我附上了2个模型脚本的截图,如果我使用时刻来转换时区,就像这样使用updateddAt: moment().utc(new Date())它工作正常。有没有办法用当前时区自动更新时间戳?

    'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('States', {

      hashCode: {
        type: Sequelize.STRING,
          unique:true,
          autoIncrement:false
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('States');
  }
};

更新表格时 enter image description here

我当地时间在电脑前 enter image description here

3 个答案:

答案 0 :(得分:3)

您应该在sequelize选项中设置timezone属性:

const sequelize = new Sequelize({
  database: 'db_name',
  username: 'username',
  password: null,
  dialect: 'mysql'
  timezone: 'utc', // your timezone comes here, ex.: 'US/Hawaii'
});

答案 1 :(得分:1)

像这样创建数据库,您将根据当地时间在更新时自动创建数据库

const sequelize = new Sequelize("db_name", "username", "password", { logging: false, host: "localhost", dialect: "mysql", dialectOptions: { // useUTC: false, //for reading from database dateStrings: true, typeCast: true, timezone: "+05:30" }, timezone: "+05:30", //for writing to database operatorsAliases: false });

答案 2 :(得分:0)

我迟到了,但这对我有用:     新的Sequelize(db,user,pass,{timezone:“ -05:00”}),其中“ -05:00”是偏移时间。

En 也是config.json ...

{
"development": {
"database": "db",
"username": "user",
"password": "pwd",
"logging": false, // verbose
"host": "localhost",
"dialect": "mysql",
"operatorsAliases": false, 
"timezone": "-05:00"
},
"test": {
...
},  
"production": {
...

}     }