'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.
Solution 1:[1]
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));
Solution 2:[2]
Intl.DateTimeFormat().resolvedOptions().timeZone
will return the client's timezone, and is useable in JavaScript, not just React.
const { timeZone } = Intl.DateTimeFormat().resolvedOptions();
console.log(timeZone);
> "America/New_York"
Solution 3:[3]
the new Date() give you the machine timezone no need for npm package to get the local time zone JavaScript give you all ready the way.
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | samanime |
Solution 2 | |
Solution 3 | TalOrlanczyk |
Solution 4 | Nikhil Vishwakarma |