JavaScript date.toLocaleString(locales, options) method
The date.toLocaleString(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. Unlike toLocaleDateString()
, this method formats both the date and the time part of the Date
object.
Syntax:
Parameters:
- locales (optional): A string or array of locale codes (e.g.,
'en-US'
for U.S. English,'fr-FR'
for French). This specifies the language and region format. - options (optional): An object that allows customization of the date and time formatting. Some common options include:
- year, month, day, hour, minute, second, etc.
- timeZone: Specifies the time zone for formatting (e.g.,
'UTC'
). - hour12: Boolean value that specifies whether to use a 12-hour format (default is based on the locale).
Returns:
- A string representing the formatted date and time according to the locale and options provided.
Example 1: Default Formatting (Locale: U.S. English)
Output:
Explanation:
- This example uses the default locale (which may vary by environment). For U.S. English (
'en-US'
), the format isMM/DD/YYYY, hh:mm:ss AM/PM
.
Example 2: Formatting with Locale (French)
Output:
Explanation:
- In French (
'fr-FR'
), the date is formatted asDD/MM/YYYY
, and the time uses the 24-hour format.
Example 3: Customizing the Date and Time Format
Output:
Explanation:
- The
options
object customizes the format, displaying the full month name ("long"
), 2-digit hour and minute, and the date in the U.S. format.
Example 4: 24-Hour Time Format with Date
Output:
Explanation:
- The date is formatted in British English (
'en-GB'
), and thehour12: false
option forces the use of a 24-hour clock.
Example 5: Displaying Only Time
Output:
Explanation:
- The
options
object includes only the time parts (hour, minute, second), without the date. This displays the time in a 12-hour format by default for U.S. English.
Example 6: Custom Time Zone
Output:
Explanation:
- The
timeZone
option is set to'UTC'
, so the date and time are displayed in the UTC time zone, including the time zone name (UTC
).
Summary:
date.toLocaleString(locales, options)
formats both the date and time based on the specified locale and options.- It supports locales for language-specific formatting and options for customizing the appearance of the date, time, time zone, and more.
- This method is highly flexible and useful for formatting dates and times in different regional formats.