Home > Back-end >  Moment JS get difference in Timezone for countdown
Moment JS get difference in Timezone for countdown

Time:11-11

I'm working with Moment JS in my Nuxt JS project. I'm building a countdown timer which needs to count down to a specific date & time, ideally, I need it to display the same countdown information based on timezone in the user's country, I need it to countdown to a date & time in Europe/London though.

This is my method:

*
** Set time left
*/
setCountdown () {
  const end = this.$moment.tz(this.$moment(this.endDate), this.$moment.tz.guess())
  const timeLeft = this.$moment(end.diff(this.$moment()))
  const daysLeft = end.diff(this.$moment(), 'days')

  this.countdown.days = daysLeft
  this.countdown.hours = timeLeft.format('HH')
  this.countdown.minutes = timeLeft.format('mm')
  this.countdown.seconds = timeLeft.format('ss')
},

The date I want to countdown to is: 2022-11-09 20:00:00 and the time in my country right now is 2022-11-09 19:00:00, despite putting this.$moment.tz.guess() within the end date, it still shows 2 hours away, where am I missing my timezone from in my code?

CodePudding user response:

use UTC if you use UTC its the universal timezone. Then when a user looks at the time it will subtract for there timezone and keep a universal time while showing each time zone correctly. https://www.nhc.noaa.gov/aboututc.shtml

moment.utc(yourDate).format()

CodePudding user response:

yes here is an example from UTC to local:

var date = moment.utc().format();
console.log(date, "- now in UTC"); 

var local = moment.utc(date).local().format();
console.log(local, "- UTC now to local"); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

  • Related