@date-fns/tz
Version:
date-fns timezone utils
37 lines (36 loc) • 1.47 kB
JavaScript
/**
* Time zone name format.
*/
/**
* The function returns the time zone name for the given date in the specified
* time zone.
*
* It uses the `Intl.DateTimeFormat` API and by default outputs the time zone
* name in a long format, e.g. "Pacific Standard Time" or
* "Singapore Standard Time".
*
* It is possible to specify the format as the third argument using one of the following options
*
* - "short": e.g. "EDT" or "GMT+8".
* - "long": e.g. "Eastern Daylight Time".
* - "shortGeneric": e.g. "ET" or "Singapore Time".
* - "longGeneric": e.g. "Eastern Time" or "Singapore Standard Time".
*
* These options correspond to TR35 tokens `z..zzz`, `zzzz`, `v`, and `vvvv` respectively: https://www.unicode.org/reports/tr35/tr35-dates.html#dfst-zone
*
* @param timeZone - Time zone name (IANA or UTC offset)
* @param date - Date object to get the time zone name for
* @param format - Optional format of the time zone name. Defaults to "long". Can be "short", "long", "shortGeneric", or "longGeneric".
*
* @returns Time zone name (e.g. "Singapore Standard Time")
*/
export function tzName(timeZone, date, format = "long") {
return new Intl.DateTimeFormat("en-US", {
// Enforces engine to render the time. Without the option JavaScriptCore omits it.
hour: "numeric",
timeZone: timeZone,
timeZoneName: format
}).format(date).split(/\s/g) // Format.JS uses non-breaking spaces
.slice(2) // Skip the hour and AM/PM parts
.join(" ");
}