在过去的 2 个小时里我一直在扯头发,起初我认为 Moment.js 是没有返回正确时间的罪魁祸首,但猫鼬 Date.now 一直在做一些邪恶的事情。
这是代码
const moment = require('moment');
const mongoose = require('mongoose');
const item = new mongoose.Schema({
time: { type: Date, default: Date.now },
time2: { type: Date }
});
如您所见,我有两个字段,一个用于猫鼬的默认日期,另一个只是用于存储日期的字段。
item.pre('save', function() {
console.log(moment()); // Showing a correct date and time
console.log(this.time); // Showing a correct date but false time
this.time2 = moment(); // When it is saved to the database, it will show a correct date but false time
});
结果是
moment("2017-01-09T19:42:48.896") // the first console.log. This is correct, the time is correct
2017-01-09T11:42:48.884Z // Second console.log. The date is correct but the time is FALSE
我想如果我这样做,一切都会解决
const item = new mongoose.Schema({
time: { type: Date, default: moment() },
time2: { type: Date, default: Date.now }
});
但是你知道控制台是什么.log对于第一个字段time
?
2017-01-09T11:42:48.884Z // it is this time which is WRONG TIME
我的猜测是猫鼬数据类型(日期)的时区检查不准确。
任何帮助将不胜感激。
你正在比较两个不同的东西。 moment()
以本地时区表示时间,Date.now
以 UTC 表示时间。猫鼬有这种方式的唯一原因是因为mongo db以这种方式保存它。此处不需要修复。
只需使用矩库将获取的猫鼬日期转换回本地时区即可。