【问题标题】:Momentjs used in Vue displays UTC time, but local time expectedVue 中使用的 Momentjs 显示 UTC 时间,但应为本地时间
【发布时间】:2018-02-10 07:37:06
【问题描述】:

momentjs 文档说:“默认情况下,moment 会以当地时间解析和显示。” (https://momentjs.com/docs/#/parsing/utc/)。

如果我直接通过 javascript 显示 moment() 的输出,确实是这样:

<div id="divLocal">
</div>    
document.getElementById("divLocal").innerHTML = moment();

输出:2017 年 9 月 1 日星期五 10:56:45 GMT+0200

如果我使用 Vuejs 做同样的事情,它会显示 UTC 时间:

<div id='app'>
  <span>{{datenow}}</span>
</div>
new Vue({
  el: '#app',
  data: {
    datenow: ''
  },
  methods: {
    time() {
      var self = this;
      this.datenow = moment();
    },
  },
  mounted: function() {
    this.time();
  }
});

输出:2017-09-01T09:02:38.169Z

示例:https://jsfiddle.net/nv00k80c/1/

有人知道为什么会这样吗?如果我在 Vue 中使用 moment().format(),输出也是正确的。但我想知道在哪里以及为什么会有所不同?

【问题讨论】:

  • 通常使用format()toString()toISOString() 来显示矩对象的值。我担心打印时刻对象的方式(不使用上述方法)取决于上下文。

标签: javascript vue.js momentjs


【解决方案1】:

Vue 调用.toJSON() 而浏览器调用toString()

正如@Vincenzo 在对您的 OP 的评论中所说,在将其传递给模板之前,您应该始终将其格式化为字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2015-01-08
    • 1970-01-01
    相关资源
    最近更新 更多