In this article, we will learn how can use moment-timezone in vue.js
Step 1: Create new Vue project:
vue create moment-timezone-demo
Step 2: Install require packages:
npm i moment-timezone
Step 3: Open App.vue file and add it in:
<template> <img alt="Vue logo" src="./assets/logo.png"> <p> UserTimeZone: {{ userTimeZone }}</p> <p> UserCity: {{ userTimeZone }}</p> <p> UserCountry: {{ userCountry }}</p> </template> <script> import { countries,zones} from 'moment-timezone/data/meta/latest.json' const timeZoneCityToCountry = {}; export default { name: 'App', data(){ return{ userCity:'', userCountry:'', userTimeZone:'' } }, mounted(){ this.fetchCountry(); }, methods:{ async fetchCountry(){ Object.keys(zones).forEach((z)=>{ const cityArr =z.split('/'); const city = cityArr[cityArr.length -1]; timeZoneCityToCountry[city] = countries[zones[z].countries[0]].name; }); this.userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; var tzArr = this.userTimeZone.split('/'); this.userCity = tzArr[tzArr.length-1]; if(this.userCity == 'Calcutta') this.userCity = 'Kolkata'; this.userCountry = timeZoneCityToCountry[this.userCity]; } } } </script> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
Code In Action: