Skip to content
Advertisement

Get client local timezone in React js

I want to get the client machine local timezone.

I tried moment-timezone npm package, with the following command

moment.tz().zoneAbbr()

But it is giving me Universal timezone ie UTC, but I want IST

Can anybody please guide me how to get client machine local time zone.

Advertisement

Answer

If you just want the timezone offset, it is pretty straight forward:

const timezoneOffset = (new Date()).getTimezoneOffset();

console.log(timezoneOffset);

That will give you whatever the computer is set to.

However, if you want to know the actual timezone, that isn’t enough, as there are many time zones for every offset.

There isn’t a super direct way to get that curiously. However, you can get it by converting Date to a string and using a little regex to grab it:

const date = new Date();
const dateAsString = date.toString();
const timezone = dateAsString.match(/(([^)]+))$/)[1];

console.log(timezone);

That’ll give you something like “Eastern Daylight Time” (for me).

If you want to convert that to an abbreviation, you’ll have to find a list of possible values and create a mapping function:

const input = 'Eastern Daylight Time';
const tz = {
 'Eastern Daylight Time': 'EDT',
 // add more here
};

const toTZAbbreviation = input => tz[input];

console.log(toTZAbbreviation(input));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement