【问题标题】:Store wrong timezone in default date and time在默认日期和时间中存储错误的时区
【发布时间】:2021-01-16 13:48:43
【问题描述】:

我正在尝试使用 mongoose 和 Node.JS 存储默认日期和时间,但不知何故,它在数据库中存储了不同的时区值。我使用“MongoDB Atlas Database”作为数据库服务器,并参考this 配置了默认时区。我也试过this改变时区,也试过“moment-timezone.js”,但没有运气。

我只想以印度标准时间格式存储默认日期和时间。

以下是我的架构代码。

const testSchema = new mongoose.Schema({
    from: String,
    to: String,
    amount: Number,
    message: {
        type: String, 
        default: ""
    },
    creationdate: { 
        type: Date, 
        default: Date.now
    }
});

请帮我解决这个问题。告诉我解决这个问题的最佳方法。

【问题讨论】:

标签: node.js mongodb mongoose mongodb-atlas


【解决方案1】:

MongoDB 将Date fields 存储为自 Unix 纪元以来以毫秒为单位的 UTC 时间戳,这是一个 64 位整数(在 JS 中为 53 位)。这也是Date.now() 是什么。数据设计中没有时区组件。

如果您需要 Date 对象的格式一致,请添加一个 virtual field 以从日期返回到所需的时区调整字符串或对象。

const testSchema = new mongoose.Schema({
    creationdate: { 
        type: Date, 
        default: Date.now
    }
});
testSchema.virtual('formattedCreationDate').get(function() {
  return this.creationdate.toLocaleString(); // or day.js/moment.js 
});

要么依赖系统时区,要么设置它,要么在虚拟吸气剂中查找时区。如果您需要每个文档的自定义时区,请将其存储在另一个字段中,并在 virtual 格式中考虑到它。

如果您使用day.jsmoment.js,虚拟可能会更容易。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多