Intl.DateTimeFormat
The Intl.DateTimeFormat object enables language-sensitive date and time formatting. It is part of the ECMAScript Internationalization API.
1. Basic Usage
The constructor takes two optional arguments: locales and options.
const date = new Date(Date.UTC(2023, 11, 25, 3, 0, 0));
// US English
console.log(new Intl.DateTimeFormat('en-US').format(date));
// "12/25/2023"
// British English
console.log(new Intl.DateTimeFormat('en-GB').format(date));
// "25/12/2023"
// Korean
console.log(new Intl.DateTimeFormat('ko-KR').format(date));
// "2023. 12. 25."
2. Using Options
You can customize the output using the options object.
Date and Time Styles
Shortcuts for standard formats.
const options = { dateStyle: 'full', timeStyle: 'long' };
const formatter = new Intl.DateTimeFormat('en-US', options);
console.log(formatter.format(date));
// "Monday, December 25, 2023 at 3:00:00 AM GMT"
Values for dateStyle and timeStyle: 'full', 'long', 'medium', 'short'.
Component Formatting
You can specify exactly which components to display and how.
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
};
console.log(new Intl.DateTimeFormat('de-DE', options).format(date));
// "Montag, 25. Dezember 2023"
3. Formatting Ranges
formatRange() formats a date range.
const date1 = new Date(Date.UTC(2023, 0, 10));
const date2 = new Date(Date.UTC(2023, 0, 20));
const fmt = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
});
console.log(fmt.formatRange(date1, date2));
// "Jan 10 – 20, 2023"
programming/javascript/vanilla/javascript programming/javascript/vanilla/date-and-time