为什么Mongodb中的ISO日期提前一天显示? [英] Why does ISO date in Mongodb display one day earlier?

查看:78
本文介绍了为什么Mongodb中的ISO日期提前一天显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

存储的日期如下所示:

<预><代码>..."date_of_birth" : ISODate("1920-01-02T00:00:00Z"),...

使用 moment,它在模型中被格式化(为了填充用于更新文档的输入),如下所示:

 作者架构.virtual('date_of_birth_update_format').get(函数(){//格式化为 JavaScript 日期格式 (YYYY-MM-DD) 以显示在输入 type="date"返回 this.date_of_birth ?时刻(this.date_of_birth).format('YYYY-MM-DD') : '';});

从集合中检索并显示,它显示为一天前的样子:

01/01/1920

如果您能帮助我解决此问题,我将不胜感激.

解决方案

来自 mongo 的日期始终采用 GMT,而您的服务器可能在其他时区.您需要在格式化之前将日期转换为 GMT.

var moment = require("moment-timezone")AuthorSchema.virtual('date_of_birth_update_format').get(function(){返回 this.date_of_birth ?时刻(this.date_of_birth).tz('GMT').format('YYYY-MM-DD') : '';});

The stored date looks like this:

...
"date_of_birth" : ISODate("1920-01-02T00:00:00Z"),
...

Using moment, it is formatted in the model (in order to populate the input for updating the document) like this:

   AuthorSchema
   .virtual('date_of_birth_update_format')
   .get(function(){
      // format in JavaScript date format (YYYY-MM-DD) to display in input type="date"
      return this.date_of_birth ? moment(this.date_of_birth).format('YYYY-MM-DD') : '';
   });

Retrieved from the collection and displayed, it displays as one day earlier like this:

01/01/1920

I would appreciate any help to resolve this.

解决方案

The date from mongo is always in GMT, and your server might be in other timezone. You need to convert date to GMT before formatting.

var moment = require("moment-timezone")

AuthorSchema.virtual('date_of_birth_update_format').get(function(){
 return this.date_of_birth ? moment(this.date_of_birth).tz('GMT').format('YYYY-MM-DD') : '';
});

这篇关于为什么Mongodb中的ISO日期提前一天显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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