Native Date i18n
by Alex Kyriakidis
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.10/plugin/localizedFormat.js"></script>
<div id="app">
<h2>Dates in multiple locales and timezones</h2>
<div>
<h2>Locales:</h2>
<button v-for="loc in locales" @click="setLocale(loc)" v-html="loc"></button>
</div>
<hr>
<div>
<h2>Timezones:</h2>
<button v-for="timezone in timezones" @click="setTimezone(timezone)" v-html="timezone"></button>
</div>
<hr>
timestamp: <input v-model.number="timestamp">
<hr>
<div :key="locale+timezone">
<h2>Output:</h2>
<p><b>Long Date:</b> {{timestamp | longDate}}</p>
<p><b>Short Date:</b> {{timestamp | shortDate}}</p>
<p><b>Short Date:</b> {{timestamp | numericDate}}</p>
</div>
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
Vue
let globalLocale = 'en-US'
let globalTimezone = 'America/New_York'
new Vue({
el: "#app",
data: {
timestamp: 1318781876,
locale: globalLocale,
timezone: 'America/New_York',
locales: ['en-US', 'en-GB', 'en-CA', 'en-AU', 'el-GR', 'zh-SG'],
timezones: ['America/New_York', 'Africa/Bissau', 'Europe/Athens', 'Europe/Amsterdam']
},
methods: {
setLocale (locale) {
this.locale = globalLocale = locale
console.log('đźš©', locale)
},
setTimezone (timezone) {
this.timezone = globalTimezone = timezone
console.log('⏰', timezone)
}
},
filters: {
longDate (value) {
let options = {
weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', timeZone: globalTimezone
}
return new Date(value*1000).toLocaleString(globalLocale, options)
},
shortDate (value) {
let options = {
weekday: 'short', year: '2-digit', month: 'short', day: '2-digit', hour: 'numeric', minute: 'numeric', timeZone: globalTimezone
}
return new Date(value*1000).toLocaleString(globalLocale, options)
},
numericDate (value) {
const options = {
month: 'numeric', year: 'numeric', day: 'numeric', timeZone: globalTimezone
}
return new Date(value*1000).toLocaleString(globalLocale, options)
}
}
})