猫鼬Date.now时间不准确

编程入门 行业动态 更新时间:2024-10-27 05:37:29
本文介绍了猫鼬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时间不准确

本文发布于:2023-10-24 02:56:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1522736.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不准确   时间   猫鼬   Date

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!