Categories
JavaScript Answers

How to detect time zone abbreviation using JavaScript?

Spread the love

Sometimes, we want to detect time zone abbreviation using JavaScript.

In this article, we’ll look at how to detect time zone abbreviation using JavaScript.

How to detect time zone abbreviation using JavaScript?

To detect time zone abbreviation using JavaScript, we can use the toLocaleTimeString method.

For instance, we write

const [, , zone] = new Date()
  .toLocaleTimeString("en-us", { timeZoneName: "short" })
  .split(" ");
console.log(zone);

to create a Date object.

And then we call toLocaleTimeString to get a locale time string in the 'en-us' locale.

We set timeZoneName to 'short' to return a time string that includes the time zone abbreviation.

Then we call split to split the string by spaces and get the time zone abbreviation from the 3rd substring.

Conclusion

To detect time zone abbreviation using JavaScript, we can use the toLocaleTimeString method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *