4

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
khushboom
  • 45
  • 1
  • 1
  • 5
  • 3
    Does this answer your question? [Getting the client's timezone offset in JavaScript](https://stackoverflow.com/questions/1091372/getting-the-clients-timezone-offset-in-javascript) – Wyck Aug 20 '20 at 13:31
  • Or this one: https://stackoverflow.com/questions/13/determine-a-users-timezone/22625076#22625076 – Wyck Aug 20 '20 at 13:32

4 Answers4

15

Intl.DateTimeFormat().resolvedOptions().timeZone will return the client's timezone.

const { timeZone } = Intl.DateTimeFormat().resolvedOptions();

console.log(timeZone);
rantao
  • 1,621
  • 4
  • 14
  • 34
10

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));
samanime
  • 25,408
  • 15
  • 90
  • 139
1

The native JS new Date() give you the machine timezone. No need for npm packages to do it.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
TalOrlanczyk
  • 1,205
  • 7
  • 21
0

Adding some additional info to @samanime answer.

you will get the time zone from this

const dateAsString = date.toString();
const timezone = dateAsString.match(/\(([^\)]+)\)$/)[1];
console.log("timezone", timezone);

Now if you want to get the abbreviations or short forms of the timezone like IST, GMT, etc. then just pick the first letter of a string in the timezone.

var matches = timezone.match(/\b(\w)/g);
var abbreviations = matches.join('');
console.log("abbreviations", abbreviations);

for example: -

timezone: Indian Standard Time

abbreviations: IST