Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to implement DateTime localization in vue.js ?

How to implement DateTime localization in vue.js ?

In this article, we will see the implementation of Date Time localization in Vue.js, along with knowing its basic implementation through the illustration.

Date() Object: In Javascript, the Date object works with dates and times. Date objects are created by the new Date() constructor.

Syntax:

const datetime = new Date();
console.log(datetime);

By default, the new Date() object will use the browser’s time zone and return the date as a full-text string. The below example illustrates the full-text string:

Tue Jan 17 2023 11:33:10 GMT+0530 (India Standard Time)

Although, the Date methods allow you to manipulate the year, month, day, hour, minute, second, and millisecond of date objects using either local time or UTC (universal, or GMT) time.

toLocaleString() Method: The toLocaleString() method returns a string with a language-sensitive representation of date format.

Syntax:

const date = new Date();
console.log(date.toLocaleString());

US English uses month-day-year order and 12-hour time with AM/PM but British English uses day-month-year order and 24-hour time without AM/PM. There are different countries and regions around the world, they have different date and time formats. Vue.js helps to localize the date time with their local definition formats. Vue.js provides an internationalization plugin named VueI18n.

The Vue I18n is an internationalization plugin of Vue.js used for localization features. It easily integrates some localization features into the Vue.js Application. It provides days and months written in local languages. When the user combines Vue and VueI18n plugins with a Web application, it supports across the global platform through localization API. Date and Time is one of the essential localization features that easily integrate the web application with help of the Vue I18n plugin.

Setting the DateTime localization in Vue.js:

  • Add the below CDN file directly For VueI18n plugin installation.
<script src="https://unpkg.com/vue-i18n@9"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>

There is an alternative approach for installing Vue and Vue-I18n plugins, i.e., installing Vue and Vue-I18n plugins/packages through NPM / Vue CLI. For this, we will follow the below step for installation:

  • Import createI18n( ) function from Vue-I18n package. Create a date Time Format(as shown below)and add those formats as parameters through createI18n(). The date Time Formats use the JSON format to add desired definition formats to localize the date and time.
const datetimeFormats = {
 'en-US': {
    short: {year: 'numeric',month: 'short',day: 'numeric'},
    long: {year: 'numeric',month: 'long',day: 'numeric',
           weekday: 'long',hour: 'numeric',minute: 'numeric',
           hour12: true}
  },
}
  • Pass the datetimeFormats as a javascript object through the parameter of createI18n(). Create a component named i18n for the Vue I18n plugin and add dateTimeFormats inside the createI18n( ) function.
// Create i18n component using createI18n( ) function 
// from Vue-I18n package for VueI18n plugin
const i18n = createI18n({
  datetimeFormats
});
  • Import createApp ( ) function from the Vue package, Load the Vue Instances using createApp( ) and use the i18n component for binding the Vue I18n plugin for the Vue instances. 
createApp(App).use(i18n).mount("#app");
  • Create a template and add <h3> element to show the date and time. For displaying desired formatted datetime in the DOM using $d() constructor as a built-in component. By default, the ‘en-US’ ( US english ) works as a locale name in the $d() constructor. If you need any other locale name format ( ‘ja’ for japanese , ‘fr’ for french ) just pass the locale format through the $d() constructor. Add the following arguments inside the $d() constructor. 
<template>
    <h1> Vue.js DateTime localization </h1> 
    <h2>English - {{ $d(new Date(), 'long') }}</h2>
    <h2>Japanese - {{ $d(new Date(), 'long', 'ja') }}</h2>
    <h2>French - {{ $d(new Date(), 'long', 'fr') }}</h2>   
</template>
<style>
    h1 {
            color: green;
        }
</style>

Where,

  • first argument: new Date() constructor as a parameter
  • second argument: format name as a parameter, it will show only DD/MM/YYYY format. (eg)- short, long 
  • third argument: localization value as a parameter, based on this parameter it chooses the desired format in datetimeFormats of JSON objects. (eg)- en(English), fr(French), de(German)

Approach 1: Create a template and bind datetime through $d( ) constructor inside double curly braces expression. Create a Script.js file for load Vue instances through Vue Components. Import Vue and vue-I18n packages, prepare desired datetimeFormats as a JSON object,s, and pass it through the CreateI18n( ) function.

Example 1: This example describes the basic implementation of the DateTime localization in Vue.js.

  • App.vue

Javascript




<template>
    <h1> Vue.js DateTime localization </h1>
    <h2>English - {{ $d(new Date(), 'long') }}</h2>
    <h2>Japanese - {{ $d(new Date(), 'long', 'ja') }}</h2>
    <h2>French - {{ $d(new Date(), 'long', 'fr') }}</h2>
</template>
<style>
    h1{color: green;}
</style>
<script>
    import {i18n} from './i18n';
    export default {
      name: 'App'
    }
</script>


  • Script.js

Javascript




//import vue and vue-i18n packages
import { createApp } from "vue";
import App from "./App.vue";
import { createI18n } from "vue-i18n";
 
//Add desired date and time formats
const datetimeFormats = {
    'ja': {
        short: { year: 'numeric',
                 month: 'short',
                 day: 'numeric' },
        long: { year: 'numeric',
                month: 'long',
                day: 'numeric',
                weekday: 'long',
                hour: 'numeric',
                minute: 'numeric'
              }
    },
    'en-US': {
        short: { year: 'numeric',
                 month: 'short',
                 day: 'numeric'
               },
        long: { year: 'numeric',
                month: 'long',
                day: 'numeric',
                weekday: 'long',
                hour: 'numeric',
                minute: 'numeric',
                hour12: true
             }
    },
    'fr': {
        short: { day: 'numeric',
                 month: 'short',
                 year: 'numeric'
               },
        long: { weekday: 'long',
                day: 'numeric',
                month: 'long',
                year: 'numeric',
                hour: 'numeric',
                minute: 'numeric',
                hour12: true
              }
    },
}
 
// Create i18n component  using createI18n( )
// for VueI18n plugin Localization
const i18n = createI18n({
    datetimeFormats
});
 
// Load Vue instances and use VueI18n component
// with instance of Vue application
createApp(App).use(i18n).mount("#app");


Output:

 

Approach 2: Create a DateTimeFormats as a JSON object for adding desired definition formats for localizing the date and time. create a drop-down list with options for localization zones. Use the v-model directive for two-way binding data for the selecting options in the drop-down list. If the end user choose any value from the drop-down list that selectedValue is matched with zones then desired Datetime localization formats of the zone will display in the UI. If you need an only day, month, and year then use short as a parameter inside the $d constructor. Use long as parameter inside $d constructor for fully formatted date and time. Add HTML templates for presenting Date and Time. initialize the data model (such as current date, and list of zones) to keep ready for binding data with Vue instances.

Example 2: In the example, we will create a date time localization using Vue.js and VueI18n Plugin.

  • App.vue

HTML




<template>
    <h1>
        Current Date and Time
    </h1>
    <h3>
        {{dateAndTime}}
    </h3>
    <h1>
        Choose Vue.js DateTime localization Zone
        <select v-model="selectedValue">
            <option v-for="item in zones"
                    :value="item">
                {{item}}
            </option>
        </select>
    </h1>
    <h2 v-if="selectedValue=='US'">
        {{ $d(new Date(), 'long') }}
    </h2>
    <h2 v-if="selectedValue=='Germany'">
        {{ $d(new Date(), 'long', 'de') }}
    </h2>
    <h2 v-if="selectedValue=='Japan'">
        {{ $d(new Date(), 'long', 'ja') }}
    </h2>
    <h2 v-if="selectedValue=='France'">
        {{ $d(new Date(), 'long', 'fr') }}
    </h2>
    <h2 v-if="selectedValue=='India'">
        {{ $d(new Date(), 'long', 'ta') }}
    </h2>
</template>
<style>
    h1 {
        color: green;
    }
</style>
 
<script>
    export default {
        name: "App",
        data() {
            return {
                dateAndTime: new Date(),
                zones: ['Germany', 'France', 'India',
                        'Japan', 'US'],
                selectedValue: null
            };
        }
    };
</script>


  • Script.js

Javascript




// import vue and vue-i18n packages
import { createApp } from "vue";
import App from "./App.vue";
import { createI18n } from "vue-i18n";
 
// Add desired date and time formats
const datetimeFormats = {
    'de': {
        short: { year: 'numeric', month: 'short', day: 'numeric' },
        long: { year: 'numeric', month: 'long', day: 'numeric',
                weekday: 'long', hour: 'numeric', minute: 'numeric' }
    },
    'ja': {
        short: { year: 'numeric', month: 'short', day: 'numeric' },
        long: { year: 'numeric', month: 'long', day: 'numeric',
                weekday: 'long', hour: 'numeric', minute: 'numeric' }
    },
    'en-US': {
        short: { year: 'numeric', month: 'short', day: 'numeric' },
        long: { year: 'numeric', month: 'long', day: 'numeric',
                weekday: 'long', hour: 'numeric', minute: 'numeric',
                hour12: true }
    },
    'fr': {
        short: { day: 'numeric', month: 'short', year: 'numeric' },
        long: { weekday: 'long', day: 'numeric', month: 'long',
                year: 'numeric', hour: 'numeric', minute: 'numeric',
                hour12: true }
    },
    'ta': {
        short: { day: 'numeric', month: 'short', year: 'numeric' },
        long: { weekday: 'long', day: 'numeric', month: 'long',
                year: 'numeric', hour: 'numeric', minute: 'numeric',
                hour12: true }
    }
}
 
// Create i18n component  using createI18n( )
// for VueI18n plugin Localization
const i18n = createI18n({
    datetimeFormats
});
 
// Load Vue instances and use VueI18n
// component with instance of Vue application
createApp(App).use(i18n).mount("#app");


Output: 

 

Example 3: In this example, we have illustrated different locale formats as parameters inside the toLocaleString() method. Here, we have also created a date object and displayed the localized date-time based on the locale name passed inside the toLocaleString( ) method.

  • App.vue 

HTML




<template>
    <h2>ar-EG - {{date1}}</h2>
    <h2>en-US - {{date2}}</h2>
    <h2>en-GB - {{date3}}</h2>
    <h2>ta-IN - {{date4}}</h2>
</template>
<style>
    h2 {
        color: green
    }
</style>
<script>
    const date = new Date();
    export default {
        name: "App",
        data() {
            return {
                date1: date.toLocaleString("ar-EG"),
                date2: date.toLocaleString("en-US"),
                date3: date.toLocaleString("en-GB"),
                date4: date.toLocaleString("ta-IN")
            };
        }
    };
</script>


Where,

  • date1: ar-EG locale used for Arabic, most Arabic-speaking countries use Eastern Arabic numerals.
  • date2: en-US locale used for US English, it uses month-day-year order and 12-hour time with AM/PM.
  • date3: en-GB locale used for British English, it uses day-month-year order and 24-hour time without AM/PM
  • date4: ta-IN locale used for Tamil, it uses day-month-year order and Tamil format for AM/PM.

Output:

 

Reference of a few localization formats:

  • ar – Arabic
  • bn – Bangladesh
  • de – German
  • el – Greek
  • en – English
  • es – Spanish
  • fr – French 
  • ja – Japanese
  • ko – Korean
  • ru – Russian
  • ta – Tamil

RELATED ARTICLES

Most Popular

Recent Comments