Search code examples
javascriptangularjsmomentjsmoment-timezone

Moment time difference won't use moment timezone but users computer time


I'm attempting to display a duration ticker for something. The start time is always in London time. It works perfectly for people in England/the same timezone, however when people in other time zones look at the duration it displays the wrong value (If you're in a timezone behind England => negative values/too small values, timezone ahead => value too large).

My solution to this was to use moment-timezone. I added the moment timezone data correctly I've attempted to use this timezone data (code simplified and separated into individual lines for easier readability):

let londonTimeNow = moment().tz('Europe/London'),
jobStartTime = moment(job.start, 'DD/MM/YYYY HH:mm:ss'),
diff = londonTimeNow.diff(jobStartTime);
duration = moment.duration(diff).format('HH:mm:ss', {trim: false});

I was hoping this would then get the current time in London and compare to the start time no matter where you are in the world. However, it seems the diff function converts the time to the user's computer time. I tried formatting the londonTimeNow to be a string, but then the diff function doesn't work. Note, I've debugged and moment().tz() is working correctly, I've tried with other time zones and it gets the correct time in the zone specified.

Any ideas?

EDIT: It seems I can get it working by manually setting the offset property of 'londonTimeNow' to 0. However this doesn't feel quite right to me. I'd prefer a solution that seems less like a hack.


Solution

  • You should specify the jobstart time in the same way you declare london time using the same timezone:

    jobStartTime = moment.tz(jobStart, 'DD/MM/YYYY HH:mm:ss','Europe/London'),
    

    This will set the job start time using the same timezone.