Faiz Mohamed Haneef
Faiz Mohamed Haneef

Reputation: 3596

Getting timezone from offset in javascript

I need to trigger time based events on my server which runs in UTC time.
In my UI, I am accepting 2 parameters

  1. The local time the trigger that needs to be run
  2. The timezone offset

I preferred to not show timezone names because it delays the page rendering and I believe its unneeded.

I checked the moment library and I don't see how to get the timezone name from timezone offset. The API moment.tz.names() returns all timezones.

IS there an API which returns, say moment.tz.name('330') = 'Asia/Kolkata' Also, if there is a solution, would DST problem be addressed

Upvotes: 5

Views: 4322

Answers (2)

user1514915
user1514915

Reputation: 107

So there will always/often be multiple names for any particular offset so there is no moment.tz.name('offset') = 'Country/Zone' api that I know of.

You can however get an array of all names based on an an offset with a simple filter function

const moment = require('moment-timezone');

const getZoneFromOffset = offsetString => moment.tz.names().filter(tz => moment.tz(tz).format('Z') === offsetString)

console.log(getZoneFromOffset("+05:30"))
// [ 'Asia/Calcutta', 'Asia/Colombo', 'Asia/Kolkata' ]

In the example above I used "+05:30" for the offset value which doesn't 100% match you use case of 330 but it demonstrates how to work the problem. You can also get an array of all the timezone names with their offsets like with a simple map on moment.tz.names()

const getZoneObjects = () =>  moment.tz.names().map(zone => ({ zone, offset: moment.tz(zone).format('Z') }))

/*
[
  { zone: 'Africa/Abidjan', offset: '+00:00' },
  { zone: 'Africa/Accra', offset: '+00:00' },
  { zone: 'Africa/Addis_Ababa', offset: '+03:00' },
  ...
*/

The examples above use Z as the timezone format but if "+5:30" doesn't match your needs you can look at https://devhints.io/moment to see the other formats you can use for example ZZ which would be "+0530" in your use case.

Upvotes: 3

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241420

When working with fixed offsets, you do not need to use Moment-Timezone. All of that functionality is provided with Moment itself, with either the parseZone or utcOffset functions.

There's an example in the documentation that matches your scenario well.

...

One use of this feature is if you want to construct a moment with a specific time zone offset using only numeric input values:

moment([2016, 0, 1, 0, 0, 0]).utcOffset(-5, true) // Equivalent to "2016-01-01T00:00:00-05:00"

Upvotes: 2

Related Questions