0 votes
in VueJS by
How to implement DateTime localization?

1 Answer

0 votes
by

You can localize the datetime with definition formats(e.g. short, long, etc).

Lets follow below steps to localize date and time,

  1. For example, you can add definition formats for English and Jappan locale as below
    const dateTimeFormats = {
      'en-US': {
        short: {
          year: 'numeric', month: 'short', day: 'numeric'
        },
        long: {
          year: 'numeric', month: 'short', day: 'numeric',
          weekday: 'short', hour: 'numeric', minute: 'numeric'
        }
      },
      'ja-JP': {
        short: {
          year: 'numeric', month: 'short', day: 'numeric'
        },
        long: {
          year: 'numeric', month: 'short', day: 'numeric',
          weekday: 'short', hour: 'numeric', minute: 'numeric', hour12: true
        }
      }
    }
  2. After that You need to specify the dateTimeFormats option of VueI18n constructor
    const i18n = new VueI18n({
      dateTimeFormats
    })
    
    new Vue({
      i18n
    }).$mount('#app')
  3. And then add them to the template
    <div id="app">
      <p>{{ $d(new Date(), 'short') }}</p>
      <p>{{ $d(new Date(), 'long', 'ja-JP') }}</p>
    </div>
  4. Finally it outputs the result
    <div id="app">
      <p>May 20, 2019</p>
      <p>2019年5月20日</p>
    </div>
...