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

Sequelize未将modified日期以UTC格式返回的问题咨询

Fixing Sequelize Timezone Mismatch Between created and modified Columns

The root cause of your issue boils down to the key difference between MySQL's DATETIME and TIMESTAMP data types:

  • DATETIME stores timestamp values exactly as they are, with no timezone conversion. Since your created column uses this type and defaults to UTC-based CURRENT_TIMESTAMP, it’s returned exactly as stored in UTC.
  • TIMESTAMP automatically converts values between the MySQL session’s timezone and UTC during storage and retrieval. Since your local timezone is UTC+2, MySQL is converting the stored UTC modified value to your local timezone when fetching it—hence the 2-hour offset you’re seeing.

Here are two clean, practical solutions to resolve this:

Solution 1: Force Sequelize to Use UTC for MySQL Sessions

The simplest fix is to configure your Sequelize connection to set the MySQL session timezone to UTC. This ensures TIMESTAMP values are retrieved in UTC (matching DATETIME behavior) without changing your database schema.

Add the timezone option to your Sequelize initialization:

const sequelize = new Sequelize('your_database', 'your_username', 'your_password', {
  host: 'localhost',
  dialect: 'mysql',
  timezone: 'UTC', // Enforces UTC for all MySQL sessions from Sequelize
  // Your existing config options...
});

After this change, both created and modified will return UTC timestamps that match exactly what’s stored in the database.

Solution 2: Standardize Column Types to DATETIME

If you want to eliminate timezone conversion entirely, you can alter the modified column to use DATETIME instead of TIMESTAMP. MySQL 5.6+ supports ON UPDATE CURRENT_TIMESTAMP for DATETIME, so you’ll keep the auto-update behavior.

Run this SQL command to modify your table:

ALTER TABLE your_table_name 
MODIFY COLUMN modified DATETIME 
DEFAULT CURRENT_TIMESTAMP 
ON UPDATE CURRENT_TIMESTAMP;

Your existing Sequelize model setup (with timestamps: false and DataTypes.DATE for both columns) will work as-is, and both columns will return raw UTC values with no conversion.

Which Solution to Pick?

  • Go with Solution 1 if you want to keep your current table structure and fix the retrieval behavior quickly.
  • Choose Solution 2 for long-term consistency, ensuring both timestamp columns behave identically and avoiding future timezone-related headaches.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:35:39