Home > Software engineering >  How can I get the UTC offset from a timezone
How can I get the UTC offset from a timezone

Time:10-24

In Node, how can I convert a time zone (e.g. Europe/Stockholm) to a UTC offset (e.g. 1 or 2), given a specific point in time? Temporal seems to be solving this in the future, but until then? Is this possible natively, or do I need something like tzdb?

CodePudding user response:

I don't know your specific use case, but in general this should be the workflow:

  1. Before you send date to the server, you send it in the ISO format (independent of the time zone). You can do it with native new Date().toISOString() method.

  2. You save ISO date in the database.

  3. Once it's returned to the client, you can parse ISO date which will automatically parse it to the user's local timezone.

CodePudding user response:

Yes, nothing native is available yet

Well, the list is well known, and easy to put in a hashmap

https://github.com/vvo/tzdb/blob/main/raw-time-zones.json

or use the library mentioned

CodePudding user response:

I would recommend not to use tzdb directly, but rather a date library that deals well with timezones. In particular, I found Luxon to be good for this, see their documentation about timezone handling. To get the offset, you just create a DateTime with the desired timezone, then get its .offset:

const dateInZone = DateTime.fromISO("2022-10-23T21:10:56Z", {
  zone: "Europe/Stockholm"
});
console.log(dateInZone.offset)

Alternatively, create a Zone instance and get its .offset() at a particular timestamp:

const zone = new IANAZone("Europe/Stockholm");
console.log(zone.offset(Date.parse("2022-10-23T21:10:56Z")));
  • Related