I am trying to generate a date object and then save the various formatted parts to variables. All it working except that I cannot seem to only generate/format the time zone name on its own.
The following code will produce 3/20/2024, EDT
but I only want EDT
to be produced.
const timeZoneFormatter1 = new Intl.DateTimeFormat("en-US", {
timeZoneName: "short",
timeZone: "America/New_York",
});
console.log(timeZoneFormatter1.format(now));
What options am I missing? How do I get it to omit the date information and only produce the time zone name?
I suppose I could just get it manually with '3/20/2024, EDT'.split(',')[1].trim()
but that feels very hacky to me.
Here’s a working demo of my attempts
const now = new Date();
const locale = "en-US";
const timeZone = "America/New_York"; //always use HQ local time zone
const dateFormatter = new Intl.DateTimeFormat(locale, {
weekday: "short",
month: "short",
day: "numeric",
timeZone,
});
console.log('Date:', dateFormatter.format(now));
const timeFormatter = new Intl.DateTimeFormat(locale, {
hour: "numeric",
minute: "numeric",
second: "numeric",
timeZone,
});
console.log('Time:', timeFormatter.format(now));
const timeZoneFormatter1 = new Intl.DateTimeFormat(locale, {
timeZoneName: "short",
timeZone,
});
console.log('TimeZone attempt #1:', timeZoneFormatter1.format(now));
const timeZoneFormatter2 = new Intl.DateTimeFormat(locale, {
month: undefined,
day: undefined,
year: undefined,
timeZoneName: "short",
timeZone,
});
console.log('TimeZone attempt #2:', timeZoneFormatter2.format(now));
const timeZoneFormatter3 = new Intl.DateTimeFormat(locale, {
timeZoneName: "short",
timeZone,
});
console.log('TimeZone attempt #3 (hacky):', timeZoneFormatter2.format(now).split(',')[1].trim());
2
Answers
he Intl.DateTimeFormat constructor does not directly support formatting only the time zone name without including other date or time components.
However, you can achieve this by formatting a fixed date that only includes the time zone information and then extracting the time zone name from it.
Working Link
You can use
DateTimeFormat.formatToParts()
and use the value of thetimeZoneName
part.This is much less hacky than doing any string manipulation.