我遇到了一个问题,即当我将记录用作 View 中的对象时,记录在数据库中的日期与显示的日期不匹配。我似乎无法弄清楚为什么记录会以不同的方式表示,但我注意到在我的数据库中,日期与仅以 yyyy-mm-dd
格式记录日期一致,时间戳为00:00:00
,例如2015-12-26 00:00:00
。这是应该保存的正确格式。出于某种原因,当我显示此值时,它以 Fri Dec 25 2015 19:00:00 GMT-0500 (EST)
格式显示日期晚了一天,因为它正在记录并以格林威治标准时间显示,这晚了 5 小时,这就是为什么两者不匹配的原因。我看不到这是在我的模型或 route 设置的。对解决这个问题有帮助吗?
AnnotationDate 是我引用的列
这是我的模型:
module.exports = function(sequelize, DataTypes) {
var Annotation = sequelize.define('annotation', {
annotationId: {
type: DataTypes.INTEGER,
field: 'annotation_id',
autoIncrement: true,
primaryKey: true
},
annotationDate: {
type: DataTypes.DATE,
field: 'annotation_date'
},
userId: {
type: DataTypes.STRING,
field: 'user_id'
}
},
{
freezeTableName: true,
getterMethods: {
annotationDateSlug: function(){
var date = new Date(this.getDataValue('annotationDate'));
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
return month+'/'+day+'/'+year;
},
},
classMethods: {
associate: function(db) {
Annotation.belongsTo(db.User)
}
}
});
return Annotation;
}
以下是值作为对象传递的方式:
appRoutes.route('/')
.get(function(req, res){
models.Annotation.findAll({
where: {
userId: req.user.user_id
},
attributes: ['annotationId', 'annotationDate'],
order: 'annotationDate DESC'
}).then(function(annotation){
res.render('pages/test.hbs',{
annotation: annotation,
user: req.user,
message: req.flash('Flash is back!')
});
})
})
.post(function(req, res){
models.Annotation.create({
annotationDate: req.body.annotationDate,
userId: req.user.user_id
}).then(function() {
res.redirect('/app');
}).catch(function(error){
res.send(error);
})
});
最佳答案
new Sequelize(db, user, pass, {
timezone: '+01:30'
});
当你定义新的 sequalize 连接到 mysql 数据库时,如果你没有定义时区而不是使用 UTC 时区,你应该提到你的时区
关于mysql - 序列化与模型对象不同的 DATE 记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34539669/