Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  119] [ 3]  / answers: 1 / hits: 28173  / 4 Years ago, thu, august 20, 2020, 12:00:00

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.


More From » timezone

 Answers
13

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));




[#50708] Friday, August 7, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maxh

Total Points: 137
Total Questions: 100
Total Answers: 103

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;