1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Format Time Zone Identifier as a JavaScript TIL

This commit is contained in:
jbranchaud
2024-05-13 12:59:15 -05:00
parent bef492fe3a
commit 03980ab291
2 changed files with 36 additions and 1 deletions

View File

@@ -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)

View File

@@ -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.