JavaScript date.toLocaleDateString(locales, options) method
The date.toLocaleDateString(locales, options)
method in JavaScript is used to convert a Date
object into a string, formatted according to the specified locales (language and region) and options. This method formats just the date part (year, month, day) based on locale conventions.
Syntax:
Parameters:
- locales (optional): A string or array of locale codes (e.g.,
'en-US'
for U.S. English,'fr-FR'
for French). It specifies the language and country format. - options (optional): An object that allows customization of the formatting. Some common options include:
year
:"numeric"
,"2-digit"
month
:"numeric"
,"2-digit"
,"long"
,"short"
,"narrow"
day
:"numeric"
,"2-digit"
- Additional options include
weekday
,era
,timeZone
, etc.
Returns:
- A string representing the formatted date according to the locale and options provided.
Example 1: Default Formatting (U.S. English)
Output:
Explanation:
- In this example, the date is formatted in the default locale (which may vary by environment). For U.S. English, the format is
MM/DD/YYYY
.
Example 2: Formatting with Locale (French)
Output:
Explanation:
- In French (
'fr-FR'
), the date is formatted asDD/MM/YYYY
.
Example 3: Customizing the Format with Options
Output:
Explanation:
- The options object specifies the format: the month as
"long"
(full month name), year as"numeric"
, and day as"numeric"
. This gives the format"Month Day, Year"
.
Example 4: Custom Format with Weekday
Output:
Explanation:
- The date is formatted with the full weekday name (
Tuesday
), short month name (Oct
), and numeric day and year. The locale'en-GB'
(British English) arranges the date asDay, DD Month Year
.
Example 5: Different Locale (Japanese Calendar)
Output:
Explanation:
- In the Japanese calendar system (
'ja-JP'
), the date includes the era (e.g., 令和 for the Reiwa era), followed by the year, month, and day.
Example 6: Two-Digit Day and Month
Output:
Explanation:
- By setting the
month
andday
to"2-digit"
, the result ensures that single-digit months and days are padded with a leading zero.
Summary:
date.toLocaleDateString(locales, options)
formats the date part of aDate
object according to locale conventions.- It supports both locales for language-specific formats and options for custom formatting.
- Useful for displaying dates in various formats based on region or user preference.