我已经将timezone
选项设置为我的时区(Europe/Zagreb
并且我也尝试过使用+01:00
),并且时间保存应该是,但是,当从数据库中读取时间时,Sequelize会将其转换为UTC。我也尝试过不同的时区,每个时区都保存正确,但从数据库读取时总是转换为UTC。
我做错了什么,或者这是一个已知的问题,是否有任何解决方法?
我创建了一个新的连接:
sequelize = new Sequelize(config.database, config.username, config.password, config);
我的配置看起来像这样:
"development": {
"username": "root",
"password": "root",
"database": "db",
"host": "localhost",
"dialect": "mysql",
"timezone": "Europe/Zagreb"
}
你可以尝试这段代码,我有同样的问题,这对我有用。
const sequelize = new Sequelize(mysql.database, mysql.user, mysql.password, {
host: mysql.host,
port:3306,
dialect:'mysql',
define: {
underscored: true,
freezeTableName: true, //use singular table name
timestamps: false, // I do not want timestamp fields by default
},
dialectOptions: {
useUTC: false, //for reading from database
dateStrings: true,
typeCast: function (field, next) { // for reading from database
if (field.type === 'DATETIME') {
return field.string()
}
return next()
},
},
timezone: '+01:00'
});
如果使用UTC,可能不需要时区。
例如,我的mysql服务器是时区'+08:00',
“mysql2”:“^ 1.6.4”,“sequelize”:“^ 4.41.2”
const sequelize = new Sequelize(database, username, password, {
host: hostname,
port: port,
dialect: 'mysql',
dialectOptions: {
typeCast: function (field, next) {
if (field.type == 'DATETIME' || field.type == 'TIMESTAMP') {
return new Date(field.string() + 'Z');
}
return next();
}
},
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});