【问题标题】:Mongodb date field not setting date in local timezoneMongodb 日期字段未在本地时区设置日期
【发布时间】:2021-06-09 17:47:37
【问题描述】:

我正在使用 Moment.js 在 Node.js 服务器中设置日期。工作正常,但由于某种原因,在创建新模型和分配日期时,时间设置得提前了两个小时。

const Comment = require('./../models/comment');
const moment = require('moment');
const { getAccessToken } = require('../services/jwt');

function createComment(req, res) {
    
    const comment = new Comment();

    const { user, content, post_slug, post_title, post_type , post_id, thumb } = req.body;

    comment.user = user;
    comment.content = content;
    comment.post_slug = post_slug;
    comment.post_id = post_id;
    comment.post_title = post_title;
    comment.post_type = post_type;
    comment.published_at = moment().format();
    comment.thumb = thumb;
    comment.deleted = false;

    console.log(comment.published_at); //2021-06-09T17:36:13.000Z
    console.log(moment().format()); //2021-06-09T19:36:13+02:00

    if (!user || !content || !post_id || !post_slug || !post_type || !post_title) {
        res.status(404).send({status: 404, message: "Ha habido un problema con la recepción de los datos."});
    } else {
        comment.save((err, commentStored) => {
            if (err) {
              res.status(500).send({message: "Error del servidor" + err})
            } else {
              if (!commentStored) {
                res.status(404).send({message: "Error al crear el comentario"});
              } else {
                res.status(200).send({comment: commentStored})
              }
            }
        });
    }
}

已在 MongoDB 设置中设置时区:

console.log(comment.published_at); //2021-06-09T17:36:13.000Z
console.log(moment().format()); //2021-06-09T19:36:13+02:00

【问题讨论】:

    标签: node.js mongodb momentjs


    【解决方案1】:

    MongoDB 中的日期值始终(且仅)存储为 UTC 时间。您需要在客户端显示当地时间或将输入时区存储在单独的字段中。

    我认为你应该更好地使用

    comment.published_at = moment().toDate()
    

    【讨论】:

      猜你喜欢
      • 2012-12-21
      • 2014-01-28
      • 2017-12-15
      • 2012-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多