When working in an application that will be used or consumed by users all over the world, is important to display the data in a way that makes sense for them.
Som data can be simple to change based on their language, like translating text, but what happens with other pieces of information?
Dates can be a complex subject. Manually formatting dates based on the language can be bug-prone. Lucky for us, Javascript exposes an API that handles this: Intl.DateTimeFormat
Matías Hernández: [0:00] The JavaScript Intl object is the API you'll use for all of your internationalization needs, allowing the engine to take care of handling the locale. This object exports a few constructors that help you achieve different internationalization tasks. [0:18] Let's first create a function that will set up a formatter object based on the Intl.DateTimeFormat. This function accepts one argument that identifies the locale that will be passed down to the DateTimeFormat constructor. The Intl object is globally available, giving you access to all its constructors.
[0:40] Now, let's format the date like USA users do. First, create a variable, get the formatter from the previous function, and pass down the corresponding locale. This is 'en-US'. Call the format method that accepts a value, in this case, a date. Let's console.log this. You can see the usual date format, mm/dd/yyyy.
[1:08] Let's try to get the same, but for Spanish. Create a variable. Call getFormatter with the 'es-ES' locale and format the value. Now, you can see that the output is different, but represent the same date, in this case as dd/mm/yyyy.
[1:31] Let's check a couple of other languages, like German, by doing the same as before, but passing the 'de' locale. Do the same for Arabic language, passing the 'ar-eg' locale. You can see that the DateTimeFormat API will parse and format a day to display it based on user language identified by the locale.
[2:00] Every Intl constructor have a second optional argument that defines different options for formatting. Let's see some of them and how that affects the output of the format for the date you just wrote. You can set the year to be displayed as two digits. You can see the output here, only show the year. Also, you can set the month to be in a long format and the day to be numeric.
[2:33] Let's check the output of this and, voilà, different day formats. There are many other options that you can use. Check them out in the MDN Docs to experiment with different date formats.