Search code examples
vue.jsinternationalizationdate-formatvuejs3quasar

how to use i18n with date format


I'm using Quasar v2 with VueJs 3. I'm trying to give different date formats for different languages, like "MM/DD/YYYY" for US and "DD.MM.YYYY" for DE. This is what I have so far:

<template>
    <p> {{ $d(date, 'long') }} <p> 
</template>

<script lang="ts">
export default defineComponent({
    name: 'PageIndex',
    setup() {
    const date = new Date(2021, 5, 10, 18)
    return {date}
  }
})
</script>

And the i18n.ts file:

const i18n = createI18n({
    locale: 'US',
    messages,
    datetimeFormats: {
        'US': {
            short: {
                year: 'numeric',
                month: 'numeric',
                day: 'numeric'
            },
            long: {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
            }

          }
})

How do I specify now that I want a different date format for every language?


Solution

  • Each locale can have its own date-time format by specifying an object under datetimeFormats, whose key is the locale name, and value defines the desired date-time format (as seen in the vue-i18n docs).

    You have one already for US, and you can add another for DE. Coincidentally, the format you want DD.MM.YYYY is achieved with the same format option you have for US:

    const i18n = createI18n({
      locale: 'US',
      messages,
      datetimeFormats: {
        US: {
          short: {
            year: 'numeric',
            month: 'numeric',
            day: 'numeric'
          },
          long: {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          }
        },
        DE: {
          short: {
            year: 'numeric',
            month: 'numeric',
            day: 'numeric'
          },
          long: {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          }
        }
      }
    })
    

    demo