How to get Australia/Sydney timezone offset in javascript/nodejs?

Viewed 3070

Based on the daylight time, Austalia/Sydney timezone offset (UTC to AEST difference) is +10:00 (from April first Sunday) and +11:00 (from October first Sunday).

The difference is 600 minutes or 660 minutes.

How to get the time difference in javascript/nodejs/momentjs ? Irrespective of server time?

2 Answers

It is very easy with Moment JS. You can try different options from Docs

var Apr = moment("2020-04-05").tz("Australia/Sydney").format('Z');
var Oct = moment("2020-10-04").tz("Australia/Sydney").format('Z');
    
console.log("Difference from April first Sunday",Apr);
console.log("Difference from October first Sunday",Oct);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.4.1/moment-timezone-with-data-2010-2020.min.js"></script>

There may well be a "better" way to do this, I haven't done any research to find out, but then why would I research

I literally just created this function using Intl.DateTimeFormat

Works in modern browsers, and modern nodejs

function getTZoffset(timeZone, d, m, y) {
  const date = Date.UTC(y, m - 1, d, 0, 0, 0);
  const tgt = Intl.DateTimeFormat('en', { timeZone, dateStyle: "short", timeStyle: 'short', hour12: false }).format(date).split(',');
  const utc = Intl.DateTimeFormat('en', { timeZone: 'UTC', dateStyle: "short" }).format(date).split(',');
  const tgtTimes = tgt[1].split(':').map(Number);
  const tgtTime = (tgtTimes[0] % 24) * 60 + tgtTimes[1]
  const utcTime = tgt[0] === utc[0] ? 0 : 24 * 60;
  return tgtTime - utcTime;
}

for (let m = 1; m <= 12; m++) {
  console.log(`Sydney/Australia 1/${m}/2020: ${getTZoffset('Australia/Sydney', 1, m, 2020)}`);
}
for (let m = 1; m <= 12; m++) {
  console.log(`America/New_York 1/${m}/2020: ${getTZoffset('America/New_York', 1, m, 2020)}`);
}

Related