0

Given the input of a timezone (eg. Phoenix, Arizona USA, which doesn't observe daylight savings time), I'd like to calculate the delta between the users timezone and the input timezone.

Below I have code that does the job. But it seems overly complex. I get the current time in the input timezone, but in a string format. So then I convert it back to a Date object. And then I do the same for the user's timezone. Seems like a lot of work.

const inputTZ = 'America/Phoenix'; // Phoenix currently observes Mountain Standard Time (MST) all year.

const offset = (
  new Date(
    new Date().toLocaleString('en-US', {timeZone: inputTZ}) // Phoenix
   ) - new Date(
    new Date().toLocaleString('en-US')   // User's local timezone
   )
) / 1000 / 60;  // convert to minutes
  
console.log("Timezone Offset with Phoenix:", offset, "Minutes");
// Output: Timezone Offset with Phoenix: -60 Minutes
// Note:   I am in Denver, which is in the same timezone as Phoenix. Denver currently observes DST.

Any easier methods?

furnaceX
  • 567
  • 2
  • 8
  • 15
  • Nope I think that's the best method without resorting to third party libraries. You could, of course, move it to a dedicated function to calculate the offset given any input string parameter. – jered Jun 18 '20 at 01:23
  • maybe with moment.js https://stackoverflow.com/a/33684910/3256489 – 4givN Jun 18 '20 at 02:00

0 Answers0