Techno Blender
Digitally Yours.

How to implement DateTime localization in vue.js ?

0 33


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 a 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/[email protected]/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 localizing 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 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 describe the basic implemention of the DateTime localization in Vue.js.

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>

Javascript

import { createApp } from "vue";

import App from "./App.vue";

import { createI18n } from "vue-i18n";

  

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 

              }

    },

}

  

const i18n = createI18n({

    datetimeFormats

});

  

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 chose 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 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.

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>

Javascript

import { createApp } from "vue";

import App from "./App.vue";

import { createI18n } from "vue-i18n";

  

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 }

    }

}

  

const i18n = createI18n({

    datetimeFormats

});

  

createApp(App).use(i18n).mount("#app");

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


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 a 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/[email protected]/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 localizing 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 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 describe the basic implemention of the DateTime localization in Vue.js.

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>

Javascript

import { createApp } from "vue";

import App from "./App.vue";

import { createI18n } from "vue-i18n";

  

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 

              }

    },

}

  

const i18n = createI18n({

    datetimeFormats

});

  

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 chose 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 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.

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>

Javascript

import { createApp } from "vue";

import App from "./App.vue";

import { createI18n } from "vue-i18n";

  

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 }

    }

}

  

const i18n = createI18n({

    datetimeFormats

});

  

createApp(App).use(i18n).mount("#app");

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

FOLLOW US ON GOOGLE NEWS

Read original article here

Denial of responsibility! Techno Blender is an automatic aggregator of the all world’s media. In each content, the hyperlink to the primary source is specified. All trademarks belong to their rightful owners, all materials to their authors. If you are the owner of the content and do not want us to publish your materials, please contact us by email – [email protected]. The content will be deleted within 24 hours.
Leave a comment