1

I'm trying to get GMT time difference for the given country.

But I get wrong results, code produces 8 hours for Sydney instead of the correct 10.

How it could be fixed?

const country = "Australia/Sydney"
const utc_ms = Date.now()
const local_s = new Date(utc_ms).toLocaleString("en-US", {timeZone: country})
const local_ms = (new Date(local_s)).getTime()
const diff = (local_ms - utc_ms)/1000/60/60 // => 8 hours

UPDATE

Seems like the problem was that the local offset is missing, below seems to be the correct code. If you know shorter version please share your answer.

const country = "Australia/Sydney"

function timezone_offset_min(country: string) {
  const local_d = new Date()
  const remote_str = local_d.toLocaleString("en-US", { timeZone: country })
  const local_ms = local_d.getTime()
  const remote_ms = (new Date(remote_str)).getTime()
  const local_remote_offset = Math.round((local_ms - remote_ms) / (60 * 1000))
  const local_offset = new Date().getTimezoneOffset()
  return local_remote_offset + local_offset
}

console.log(timezone_offset_min(country))
Alex Craft
  • 13,598
  • 11
  • 69
  • 133

1 Answers1

1

Try to use moment.js. For detailed explanation, answer of this question is already posted Here. Hope this post will help in solving this problem.

Furqan Aziz
  • 1,094
  • 9
  • 18