Borislav Hadzhiev
Tue Jan 18 2022·2 min read
Photo by Eldar Nazarov
Use the toLocaleDateString
method to get the time zone abbreviation. The
method can be passed an options
object where the timeZoneName
property can
be set to short
to get the time zone abbreviation.
// 👇️ GMT+2 (with locale en-US) console.log( new Date() .toLocaleDateString('en-US', { day: '2-digit', timeZoneName: 'short', }) .slice(4), ); // 👇️ OEZ (with locale de-DE) console.log( new Date() .toLocaleDateString('de-DE', { day: '2-digit', timeZoneName: 'short', }) .slice(4), ); // 👇️ "Europe/Sofia" console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
We used the toLocaleDateString method to get an abbreviation of the visitor's default time zone.
The 2 parameters we passed to the method are:
locales
- a string with a BCP 47 language tag or an array of such strings.
You can use any of the available locales, e.g. es-MX
for Mexico or en-CA
for Canada. If you need more information about this parameter, check out the
MDN docs.options
object, where we set the day
and timeZoneName
properties. Read
more about the options
object in the
MDN docs.The timeZoneName
property represents the localized time zone name and can be
set to a value of long
or short
.
Here is how the output looks when the timeZoneName
property has a value of
long
.
// 👇️ Eastern European Standard Time (en-US locale) console.log( new Date() .toLocaleDateString('en-US', { day: '2-digit', timeZoneName: 'long', }) .slice(4), ); // 👇️ Osteuropaeische Normalzeit (de-DE locale) console.log( new Date() .toLocaleDateString('de-DE', { day: '2-digit', timeZoneName: 'long', }) .slice(4), );
We also set the day
property to 2-digit
, which we used to slice off the date
part from the string and only return the time zone name.
You can use the Intl.DateTimeFormat
method if you need to get the full name of
the visitor's time zone.
// 👇️ "Europe/Sofia" console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
The
resolvedOptions
method returns an object, which has a timeZone
property, which represents the
visitor's default time zone.