Search code examples
vue.jsdayjs

Vue, dayjs wrong output on template


In the console log, I have 15:14, but in the template, I got 12:14. Why?

<template>
    <span>{{ date }}</span> <!-- **expected** Thu, 25 Feb 2021 15:14:04 Thu, **got** 25 Feb 2021 12:14:04 GMT -->
</template>

<script>
export default {
  computed: {
    date() {
      const date = getStatusDate(); // returns string 2021-02-25 15:14:04
      return dayjs(date, 'YYYY-MM-DD HH:mm:ss+z')
    }
  }
}
</script>

Solution

  • Since the input date string has no timezone specified, the underlying Date object in dayjs assumes local timezone. The template's string interpolation leads to dayjs().toString(), which uses Date.prototype.toUTCString(), causing the display of different times.

    The solution is to use dayjs().format() to control the format of the output string:

    dayjs(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
    

    const getStatusDate = () => '2021-02-25 15:14:04'
    
    new Vue({
      el: '#app',
      computed: {
        date() {
          const date = getStatusDate()
          return dayjs(date, 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss')
        }
      }
    })
    <script src="https://unpkg.com/vue@2.6.12"></script>
    <script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>
    
    <div id="app">
      <p>{{ date }}</p>
    </div>