From 03980ab29195680bc7f32def02b98206a1f8c9e9 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 13 May 2024 12:59:15 -0500 Subject: [PATCH] Add Format Time Zone Identifier as a JavaScript TIL --- README.md | 3 +- javascript/format-time-zone-identifier.md | 34 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 javascript/format-time-zone-identifier.md diff --git a/README.md b/README.md index 2d27f20..b381bfd 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1427 TILs and counting..._ +_1428 TILs and counting..._ --- @@ -462,6 +462,7 @@ _1427 TILs and counting..._ - [Find Where Yarn Is Installing Binaries](javascript/find-where-yarn-is-installing-binaries.md) - [for...in Iterates Over Object Properties](javascript/for-in-iterates-over-object-properties.md) - [Format A Decimal To A Fixed Number Of Digits](javascript/format-a-decimal-to-a-fixed-number-of-digits.md) +- [Format Time Zone Identifier](javascript/format-time-zone-identifier.md) - [Formatting Values With Units For Display](javascript/formatting-values-with-units-for-display.md) - [Freeze An Object, Sorta](javascript/freeze-an-object-sorta.md) - [Generate A V4 UUID In The Browser](javascript/generate-a-v4-uuid-in-the-browser.md) diff --git a/javascript/format-time-zone-identifier.md b/javascript/format-time-zone-identifier.md new file mode 100644 index 0000000..7073fc6 --- /dev/null +++ b/javascript/format-time-zone-identifier.md @@ -0,0 +1,34 @@ +# Format Time Zone Identifier + +Though there are surely libraries that can help with this task, we now have +full support in the [`Intl.DateTimeFormat` +API](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) +for formatting a date's time zone identifier in various ways. + +To do this, we have to create a formatter specifying the locale, the `timeZone` +option, and any formatting options. For the formatting, I'll try the +`timeZoneName` with both `short` and `longGeneric`. + +Then we `formatToParts` on any date object and extract the `timeZoneName` +value: + +```javascript +const options = { timeZone: 'America/Chicago', timeZoneName: "short" } +const formatter = new Intl.DateTimeFormat("en-US", options) + +formatter.formatToParts(new Date()).find((part) => part.type === "timeZoneName").value +//=> 'CDT' +``` + +Now, let's try this for `longGeneric`: + +```javascript +const options = { timeZone: 'America/Chicago', timeZoneName: "longGeneric" } +const formatter = new Intl.DateTimeFormat("en-US", options) + +formatter.formatToParts(new Date()).find((part) => part.type === "timeZoneName").value +//=> 'Central Time' +``` + +There are several more options for the `timeZoneName` as well as a bunch more +you can do with the `Intl.DateTimeFormat` API.