JavaScript Intl.DateTimeFormat
Intl.DateTimeFormat
is a built-in object in JavaScript that enables language-sensitive date and time formatting. It allows developers to create date and time strings that are formatted according to the conventions of a specific locale, making it easier to present dates and times in a way that users expect.
Syntax
locales
(optional): A string with a BCP 47 language tag, or an array of such strings, that specifies the locale(s) to be used.options
(optional): An object that contains options to customize the formatting.
Common Options
localeMatcher
: Specifies the locale matching algorithm to use. Possible values are"lookup"
or"best fit"
.timeZone
: A string representing the time zone to use. E.g.,"UTC"
,"America/New_York"
.year
: Specifies how to display the year. Options:"numeric"
,"2-digit"
.month
: Specifies how to display the month. Options:"numeric"
,"2-digit"
,"narrow"
,"short"
,"long"
.day
: Specifies how to display the day. Options:"numeric"
,"2-digit"
.hour
: Specifies how to display the hour. Options:"numeric"
,"2-digit"
.minute
: Specifies how to display the minute. Options:"numeric"
,"2-digit"
.second
: Specifies how to display the second. Options:"numeric"
,"2-digit"
.timeZoneName
: Specifies whether to display the time zone name. Options:"short"
,"long"
.
Example 1: Basic Formatting
Output:
Explanation:
- The date is formatted according to the US conventions (MM/DD/YYYY).
Example 2: Formatting with Options
Output:
Explanation:
- The formatter includes options to display the full month name, the numeric day and year, the time in 12-hour format, and the time zone abbreviation.
Example 3: Locale-Sensitive Formatting
Output:
Explanation:
- This example formats the date according to French conventions, displaying the full day and month names, along with the time.
Example 4: Using Different Time Zones
Output:
Explanation:
- The date is formatted according to the Tokyo time zone, showing the local time and the time zone abbreviation.
Summary
Intl.DateTimeFormat
is a powerful tool for formatting dates and times in a way that is appropriate for different locales and time zones.- It allows developers to create user-friendly date and time strings that conform to local customs, enhancing the usability and internationalization of applications.