I am trying to extract only timeZoneName from Date object. I did it in english using regex but, how to do it in different languages like french. I realized regex is not an option for this. How do I get only timeZoneName?
let d = new Date().toString();
let finalD = (d.substring(d.search("GMT"), d.length));
const [gmt, time] = finalD.split('(');
const timezone = time.replace(/\)/g, "");
console.log(gmt, timezone);
In most modern JavaScript environments you can use the ECMAScript Internationalization API to achieve this. In particular DateTimeFormat
exposes functions that you can use.
const d1 = new Date(2020, 0, 1);
const d2 = new Date(2020, 6, 1);
const dtf1 = new Intl.DateTimeFormat('en', { timeZoneName: 'long'});
const dtf2 = new Intl.DateTimeFormat('fr', { timeZoneName: 'long'});
console.log(dtf1.formatToParts(d1).find(x => x.type ==='timeZoneName').value);
console.log(dtf1.formatToParts(d2).find(x => x.type ==='timeZoneName').value);
console.log(dtf2.formatToParts(d1).find(x => x.type ==='timeZoneName').value);
console.log(dtf2.formatToParts(d2).find(x => x.type ==='timeZoneName').value);
In the above example, I show formatters for two different languages and two different dates. This highlights that the value will be different depending on whether standard time or daylight time is in effect.
A couple of other points:
If you omit the Date
object passed to formatToParts
, it will use the current date and time (same as new Date()
).
If you pass undefined
instead of a language code, it will use the user's default language.
You can also use the timeZoneName
option when calling other methods on DateTimeFormat
, or when calling toLocaleString
and similar functions on a Date
object instance. I used formatToParts
to make it easy to get just the time zone name without doing any string manipulation.
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