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.
One liner:
new window.Intl.DateTimeFormat().resolvedOptions().timeZone
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With