Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the timezone string of the browser in Javascript?

I want to display on my webpapge the full-name of the user's Timezone. For example:

Eastern Standard Time (North America)
Pacific Daylight Time (North America)
West Africa Time

How can I do this in Javascript? I have seen solutions that render something like this: America/New_York. But that's not really what I'm looking for.

like image 973
Saqib Ali Avatar asked Feb 22 '16 05:02

Saqib Ali


2 Answers

One liner:

new window.Intl.DateTimeFormat().resolvedOptions().timeZone
like image 147
eddyP23 Avatar answered Oct 13 '22 11:10

eddyP23


You appear to be asking for a human-readable description of the user's current time zone, in the user's current language, at the current point in time.

In most modern browsers and other environments that fully support the ECMAScript Internationalization API this is best extracted as follows:

// Get a specific point in time (here, the current date/time):
const d = new Date();

// Get a DateTimeFormat object for the user's current culture (via undefined)
// Ask specifically for the long-form of the time zone name in the options
const dtf = Intl.DateTimeFormat(undefined, {timeZoneName: 'long'});

// Format the date to parts, and pull out the value of the time zone name
const result = dtf.formatToParts(d).find((part) => part.type == 'timeZoneName').value;

For example, in my Chrome 79 browser on Windows in winter, it returns "Pacific Standard Time". The same code in summer will return "Pacific Daylight Time". If you want to reflect the description of the time zone that is in effect at a particular time of the year, then create the Date object at that particular time.

In older environments that don't support the Intl API, you can try extracting part of the time zone name from the Date.toString output like this:

var s = new Date().toString().match(/\((.*)\)/).pop();

This only works because the output of the toString function on the Date object is left up to the implementation to define, and many implementations happen to supply the time zone in parenthesis, like this:

Sun Feb 21 2016 22:11:00 GMT-0800 (Pacific Standard Time)

If you were looking for a generic name, such as simply "Pacific Time" - sorry, that's not available.

like image 28
Matt Johnson-Pint Avatar answered Oct 13 '22 11:10

Matt Johnson-Pint