Crocsx
Crocsx

Reputation: 7640

how to get a UTC offset from a timezone in js

In Vanilla JavaScript (i.e. without using Moment.js).

I have a server returning a timezone string, like Asia/Tokyo America/New_York etc... That timezone is independent from the user current timezone. So the server can return Asia/Tokyo when my current OS timezone is America/New_York

from the server given timezone, I would like to format it to something like =>

UTC+09:00 Asia/Tokyo

So in simple, I just want, from a given timezone, to find the UTC Offset of that timezone.

There is a native function getTimezoneOffset in JS, but I can't find a setTimezone

I tried to do something like

var d = new Date()
new Date(d.toLocaleString('en-US', { timeZone: 'Asia/Tokyo' })).getTimezoneOffset()

but this always return my current offset.

How can I do this ?

Upvotes: 4

Views: 2058

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30725

You can use Date.toLocaleString() to calculate this, this solution is slightly hacky, since we're formatting a date, then parsing. But it should do what you wish.

I'm converting to the "sv" date format, since it's very similar to ISO-8601, then parsing to get the UTC date.

Note: The offset will be negative for timezones east of the Greenwich meridian, this is the same as the IANA convention. You can simply reverse if you wish to get UTC offset as minutes ahead of UTC. Also, I'm rounding at then end, since our original date will contain a millisecond component that we're not interested in.

function getUTCOffset(date, timeZone) {
    const dateComponents = date.toLocaleString("sv", { timeZone }).split(/[\-\s:]/);
    // Months are zero-based in JavaScript
    dateComponents[1] = dateComponents[1] - 1;
    const utcDate = Date.UTC(...dateComponents);
    return Math.round((date - utcDate) / 60 / 1000);
}

console.log(getUTCOffset(new Date(), 'Asia/Tokyo'));
console.log(getUTCOffset(new Date(), 'America/Los_Angeles'));

Upvotes: 4

Related Questions