猫鼬Date.now时间不准确 [英] Mongoose Date.now time is not accurate

查看:161
本文介绍了猫鼬Date.now时间不准确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去2个小时我一直在梳理头发,起初我以为Moment.js是未返回正确时间的罪魁祸首,但那是猫鼬Date.now一直在做一些邪恶的事情.

I've been tearing my hair out for the past 2 hours, At first I thought Moment.js is the culprit for not returning a correct time, but it was mongoose Date.now that has been doing some evil stuff.

这是代码

const moment = require('moment');
const mongoose = require('mongoose');

const item = new mongoose.Schema({
   time: { type: Date, default: Date.now },
   time2: { type: Date }
});

如您所见,我有两个字段,一个是猫鼬的默认日期,另一个是用于存储日期的字段.

As you can see I have two fields, one is for the default date from mongoose and the other one is just a field for storing 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

我认为如果我这样做,一切都会解决

I thought If I do this everything will be solved

const item = new mongoose.Schema({
       time: { type: Date, default: moment() },
       time2: { type: Date, default: Date.now }
 });

但是您知道第一个字段time的console.log是什么吗?

But you know what is the console.log for the first field which is time?

2017-01-09T11:42:48.884Z // it is this time which is WRONG TIME

我的猜测是猫鼬数据类型(日期)的时区检查不正确.

My guess would be that mongoose data type which is Date has an inaccurate timezone check.

任何帮助将不胜感激.

推荐答案

您正在比较两个不同的东西. moment()给出本地时区的时间,而Date.now给出UTC时间.猫鼬有这种方式的唯一原因是因为mongo db用这种方式保存了它.此处无需修复.

You are comparing two different things. moment() gives time in local time zone and Date.now is time in UTC. The only reason mongoose has that way is because mongo db saves it that way. No fix is required here.

只需使用矩库将获取的猫鼬日期转换回本地时区即可.

Just convert the fetched mongoose date back to local time zone using moment library.

这篇关于猫鼬Date.now时间不准确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆