If you have a date object and want to display the time to the user, it can be useful to display the timezone as well. The only way to show the timezone normally is to display the full date in a long format.
const date = new Date('2022-11-29T19:00:00-05:00');
date.toLocaleString('en-US', {
timeZoneName: 'short',
});
// 11/29/2022, 7:00:00 PM EST
However, we’re not allowed to pass other options like dateStyle
if we use timeZoneName
. So if we want to format the date ourselves, we can use the Intl.DateTimeFormat()
formatter to get the date back in an array of pieces. The last piece will be our time zone.
const date = new Date('2022-11-29T19:00:00-05:00');
const dateParts = new Intl.DateTimeFormat('en-US', {
timeZoneName: 'short',
}).formatToParts(date);
/** dateParts
{
[
{ type: 'month', value: '11' },
{ type: 'literal', value: '/' },
{ type: 'day', value: '29' },
{ type: 'literal', value: '/' },
{ type: 'year', value: '2022' },
{ type: 'literal', value: ', ' },
{ type: 'timeZoneName', value: 'EST' }
]
}
*/
const timeZone = dateParts.pop().value
console.log(timeZone)
// EST
You can also get some other formats by changing timeZoneName
:
{
"short": "EST",
"long": "Eastern Standard Time",
"shortOffset": "GMT-5",
"longOffset": "GMT-5:00",
"shortGeneric": "ET",
"longGeneric": "Eastern Time"
}