'Using timezones with @nuxtjs/moment
We use the @nuxtjs/moment (https://www.npmjs.com/package/@nuxtjs/moment) package in our nuxt application.
In our app we want to display GMT-timestamps in the users timezone like so:
<div>{{ $moment("2019-04-25 19:01:03").fromNow() }}</div>
But on my PC the result is just
2 hours ago because I'm based in germany.
Is there any way to set the default timezone to GMT so that the function works correctly? I've looked into moment-timezone but have no idea how to implement that to a nuxt application.
Solution 1:[1]
Looks like there's an open issue in the repo for this here. What I'd suggest doing instead is adding moment-timezone as a plugin until that feature is merged.
Install
npm install moment-timezone
Add the plugin import
// nuxt.config.js
export default {
plugins: ['~/plugins/moment-timezone-inject.js']
}
Create the plugin
// ~/plugins/moment-timezone-inject.js
const moment = require('moment-timezone');
export default ({ app }, inject) => {
// Inject into context, Due instances, and Vuex store
inject('moment_timezone', moment)
}
Usage
// Add whatever timezone you need
<div>{{ $moment_timezone("2019-04-25 19:01:03").tz("Asia/Taipei"); }}</div>
Solution 2:[2]
Update
You can enable moment-timezone via the timezone option, by adding this to nuxt.config.js:
export default {
buildModules: [
'@nuxtjs/moment'
],
moment: {
timezone: true
}
}
Setting default Time Zone:
moment: {
defaultTimezone: 'America/Los_Angeles'
}
More info: https://www.npmjs.com/package/@nuxtjs/moment
Solution 3:[3]
It depends on which country the date you put in the $moment function is for, you should set the same in this section
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gabriel Robert |
| Solution 2 | Almog Langleben |
| Solution 3 | mohammad |
