4 ms·
Some protips on Intl APIs (to simplify the examples in the article): 1) They default to the user's locale as set in their Browser settings and you don't ever n
by WorldMaker 4y ago
Some protips on Intl APIs (to simplify the examples in the article):
1) They default to the user's locale as set in their Browser settings and you don't ever need to look up navigator.language yourself.
The trick to using an options object to something like Intl.DateTimeFormat where the options object is after the locale name is to pass `undefined` as the locale to opt in to the default behavior. (I wish they had swapped the order in constructors to make this easier/more obvious.)
In the article's case can save a line and:
const dateFormatter = new Intl.DateTimeFormat(undefined, { timeZone: 'UTC' })
Also, constructing a formatter like this is for better reuse of the formatter with saved options (ie, moving this up and out of the function defined in the articles instead of building a new one every function call).
2) There's one more important way to shrink this article's example down, many built-in JS types including `Date` as all these examples show now include a function directly to format using the appropriate Intl formatter called `toLocaleString`. In this case: Date.prototype.toLocaleString(locale, options) takes all the same options. You can replace the article's formatDate function entirely with toLocaleString:
const parsedQuote = `
<q>${content}</q> <br>
<p>- ${author}</p><br>
<p>Added on ${dateAdded.toLocaleString(undefined, { timeZone: 'UTC' })}</p>`