javascript - 为什么 Mongodb 中的 ISO 日期显示提前一天?

标签 javascript node.js mongodb mongoose mongoose-schema

存储的日期如下所示:

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

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

   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') : '';
   });

从集合中检索并显示,它显示为前一天,如下所示:

01/01/1920

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

最佳答案

来自 mongo 的日期始终为 GMT,并且您的服务器可能位于其他时区。格式化之前,您需要将日期转换为 GMT。

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') : '';
});

关于javascript - 为什么 Mongodb 中的 ISO 日期显示提前一天?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46452658/

相关文章:

javascript - 具有多个图层的自定义 map 类型

javascript - 在 NodeJS 中使用参数获取 Express Route URL

node.js - Connect-mongo语法错误: unexpected token =>

javascript - 在react-native中导入npm模块时出错

javascript - 动态创建的PHP数组字段不使用mysql将数据保存在表中

node.js - 为什么 Express res.render 在控制台中转储渲染输出(EJS 模板)?

javascript - Mongo 中存储的数组无法与具有相同长度和值的 native JavaScript 数组进行深度断言比较

c# - 对应用于 MongoDB 中数组元素中每个项目的函数进行排序

javascript - jquery 移动可折叠 ListView 不适用于 li 标签

javascript - 从node.js运行webgl JS文件