【问题标题】:How to convert the momentJs time to local time如何将momentJs时间转换为当地时间
【发布时间】:2021-02-03 17:52:15
【问题描述】:

在 mongoose 中创建项目时,我试图将本地时间保存为默认时间

const ItemSchema = new mongoose.Schema({
  item_name: { type: String, required: true },
  shop_id: { type: mongoose.Schema.Types.ObjectId, ref: "Shop" },
  createTime: { type: Date, default: moment().utcOffset(7) },
});

如您所见,我试图抵消moment UTC 时间,但它不起作用?我做错了什么?

【问题讨论】:

  • 如果你只使用没有utcOffset的moment(),不能得到当地时间?因为这个函数返回从 UTC 的实际偏移量,通常使用 new Date() 到本地时间

标签: node.js mongoose momentjs


【解决方案1】:

您只是将 moment 实例传递给您的 createTime 字段,这是行不通的。使用.utcOffset()将日期转换为您当地的时区后,您需要将其提取为可以被猫鼬理解为日期的东西。根据momentjs doccumentation,修复应该像在你的moment对象中添加.format()一样简单:moment().utcOffset(7).format()

【讨论】:

    【解决方案2】:

    moment() 不会返回新的 Date() 猫鼬模式需要一个 Date 实例 试试:

    const ItemSchema = new mongoose.Schema({
      item_name: { type: String, required: true },
      shop_id: { type: mongoose.Schema.Types.ObjectId, ref: "Shop" },
      createTime: { type: Date, default: new Date(moment().utcOffset(7).format()) },
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-30
      • 2013-03-12
      • 2015-09-26
      • 1970-01-01
      • 2016-01-19
      • 2019-01-15
      • 1970-01-01
      相关资源
      最近更新 更多