javascriptdatetime-format

How to get just the time zone name from Intl.DateTimeFormat?


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());


Solution

  • You can use DateTimeFormat.formatToParts() and use the value of the timeZoneName part.

    This is much less hacky than doing any string manipulation.

    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,
    });
    
    const parts = timeZoneFormatter1.formatToParts(now);
    console.log('parts:', parts);
    
    const tzName = parts.find(x => x.type === 'timeZoneName').value;
    console.log('timeZoneName:', tzName);