Muke
Muke

Reputation: 23

Momentjs used in Vue displays UTC time, but local time expected

The momentjs documentation says: 'By default, moment parses and displays in local time.' (https://momentjs.com/docs/#/parsing/utc/).

If I display the output of moment() directly via javascript, thats indeed the case:

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

Output: Fri Sep 01 2017 10:56:45 GMT+0200

If I do the same using Vuejs, it shows UTC time:

<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();
  }
});

Output: 2017-09-01T09:02:38.169Z

Example: https://jsfiddle.net/nv00k80c/1/

Someone has an idea why this is happening? If I use moment().format() in Vue, the output is also correct. But I wonder where and why there is a difference?

Upvotes: 1

Views: 2729

Answers (1)

Linus Borg
Linus Borg

Reputation: 23998

Vue calls .toJSON() while the browser calls toString()

As @Vincenzo said in a comment to your OP, you should always format into a string before passing it to the template.

Upvotes: 2

Related Questions