Node.js
Intl.DateTimeFormat
Learn localization with Intl.DateTimeFormat.
Intl.DateTimeFormat
To display a date to users, Intl.DateTimeFormat localizes it. It takes a locale code and options; it formats output according to that locale.
Example: new Intl.DateTimeFormat("tr-TR", { day: "numeric", month: "long", year: "numeric" }). You format with .format(date). tr-TR is Turkish for Turkey; en-US American English; de-DE German. month: "long" gives the full month name (March); month: "short" the abbreviation (Mar); month: "numeric" the number (3). For timezone add timeZone: "UTC"; the output then does not depend on the machine's timezone. This is the standard way to display dates in multilingual apps.
Locale codes
A locale code has the language-region form: tr-TR, en-US, en-GB, de-DE, fr-FR, ja-JP. The same language uses different formats in different regions: en-US uses month/day/year order, en-GB day/month/year.
Example: new Intl.DateTimeFormat("en-US").format(new Date("2024-03-15")) gives 3/15/2024; for en-GB it is 15/03/2024. Without a locale Node.js uses the machine default, which makes tests fragile. Always pass an explicit locale in tests. With month: "long" the month name comes in the locale's language: "Mart" in tr-TR, "March" in en-US. In this lesson's exercise we will use the tr-TR locale together with the UTC timezone.
Exercise Print a date in a localized format
Define const date = new Date("2024-03-15T00:00:00Z");. Create a formatter with const fmt = new Intl.DateTimeFormat("tr-TR", { day: "numeric", month: "long", year: "numeric", timeZone: "UTC" });. Print with console.log(fmt.format(date)).
Show example solution
const date = new Date("2024-03-15T00:00:00Z");
const fmt = new Intl.DateTimeFormat("tr-TR", { day: "numeric", month: "long", year: "numeric", timeZone: "UTC" });
console.log(fmt.format(date));
Test yourself
-
Match each option to its output
- day: numeric
- Day number
- month: long
- Full month name
- year: numeric
- Year number
- timeZone: UTC
- UTC timezone
-
What month name does Intl.DateTimeFormat("tr-TR", { month: "long" }) give?
new Intl.DateTimeFormat("tr-TR", { month: "long" }).format(new Date("2024-03-15"))
Show answer
Mart — In the tr-TR locale March is written as 'Mart'.
-
Complete the DateTimeFormat call
const fmt = new Intl.____("tr-TR", { day: "numeric", month: "long", year: "numeric", timeZone: "UTC" });
Show answer
const fmt = new Intl.DateTimeFormat("tr-TR", { day: "numeric", month: "long", year: "numeric", timeZone: "UTC" });
Next lesson: performance.now