You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sequelize连接MySQL时时区配置不生效,如何正确设置?

Sequelize时区配置不生效问题

已配置Sequelize连接的时区,但查询返回的createdAt和updatedAt仍为UTC时间,配置代码如下:

DB_CONFIG: {
  dialect: 'mysql',
  host: '127.0.0.1',
  username: 'root',
  password: '******',
  database: '******',
  omitNull: true,
  dialectOptions: {
    useUTC: false, //for reading from database
    timezone: '+08:00'
  },
  timezone: '+08:00' //for writing to database
}

数据表模型代码:

const { DataTypes } = require('sequelize')
const sequelize = require('./db')

const attributes = {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
  },
  givenName: {
    type: DataTypes.STRING,
    allowNull: false
  },
  courtesyName: {
    type: DataTypes.STRING,
  },
  parentId: {
    type: DataTypes.INTEGER
  },
  generation: {
    type: DataTypes.INTEGER,
    allowNull: false
  },
  birth: {
    type: DataTypes.STRING,
  },
  death: {
    type: DataTypes.STRING,
  },
  memo: {
    type: DataTypes.STRING,
  }
}

module.exports = sequelize.define('master', attributes)

查询结果返回的时间仍为UTC时区:

"updatedAt": "2022-11-08T02:31:22.381Z",
"createdAt": "2022-11-08T02:31:22.381Z"

解决方案

1. 同步MySQL数据库时区

先检查MySQL自身的时区设置,执行SQL命令:

SELECT @@global.time_zone, @@session.time_zone;

若返回值不是+08:00或Asia/Shanghai,需修改数据库配置:

  • 编辑MySQL配置文件(如my.cnf/my.ini),添加:
    default-time-zone = '+08:00'
    
  • 重启MySQL服务,或临时执行以下SQL生效:
    SET GLOBAL time_zone = '+08:00';
    SET time_zone = '+08:00';
    FLUSH PRIVILEGES;
    

2. 修正Sequelize核心配置

调整配置项,确保时区参数优先级正确(Sequelize v6+版本):

DB_CONFIG: {
  dialect: 'mysql',
  host: '127.0.0.1',
  username: 'root',
  password: '******',
  database: '******',
  omitNull: true,
  timezone: '+08:00', // 统一控制读写时区,优先级高于dialectOptions
  dialectOptions: {
    useUTC: false,
    timezone: '+08:00'
  },
  // 可选:自定义时间字段序列化规则
  define: {
    timestamps: true,
    // 将时间序列化为本地时区格式
    hooks: {
      afterFind: (instance) => {
        if (instance.createdAt) instance.createdAt = instance.createdAt.toLocaleString()
        if (instance.updatedAt) instance.updatedAt = instance.updatedAt.toLocaleString()
      }
    }
  }
}

3. 确认模型时间字段类型

Sequelize默认自动添加createdAt/updatedAt,若手动定义需确保类型为DataTypes.DATE:

// 示例手动定义时间字段
createdAt: {
  type: DataTypes.DATE,
  allowNull: false
},
updatedAt: {
  type: DataTypes.DATE,
  allowNull: false
}

4. 查询时强制转换时区(兜底方案)

若以上配置仍不生效,可在查询中显式转换时区:

const result = await Master.findAll({
  attributes: [
    'id',
    'givenName',
    [sequelize.fn('CONVERT_TZ', sequelize.col('createdAt'), '+00:00', '+08:00'), 'createdAt'],
    [sequelize.fn('CONVERT_TZ', sequelize.col('updatedAt'), '+00:00', '+08:00'), 'updatedAt']
  ]
});

内容的提问来源于stack exchange,提问作者rossroma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 21:21:03