JavaScript date.toLocaleTimeString(locales, options) method
The date.toLocaleTimeString(locales, options)
method in JavaScript is used to convert the time portion of a Date
object into a string, formatted according to the specified locales (language and region) and options. Unlike toLocaleString()
, this method focuses only on the time component (hours, minutes, and seconds).
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 for customizing the time formatting. Some common options include:
- hour, minute, second
- hour12: Boolean value specifying whether to use a 12-hour format (default is based on locale).
- timeZone: Specifies the time zone for formatting (e.g.,
'UTC'
).
Returns:
- A string representing the formatted time according to the locale and options provided.
Example 1: Default Formatting (Locale: U.S. English)
Output:
Explanation:
- This example uses the default locale (
en-US
in this case), and the time is displayed in a 12-hour format with AM/PM.
Example 2: Formatting Time in 24-Hour Format (British English)
Output:
Explanation:
- For British English (
'en-GB'
), the time is displayed in 24-hour format without AM/PM.
Example 3: Customizing Time Format (Showing Only Hours and Minutes)
Output:
Explanation:
- The
options
object customizes the format to show only the hours and minutes in 12-hour format with AM/PM.
Example 4: 24-Hour Time with Seconds
Output:
Explanation:
- The
hour12: false
option forces the use of the 24-hour clock, showing hours, minutes, and seconds.
Example 5: Custom Time Zone (UTC)
Output:
Explanation:
- The time is formatted in UTC time zone and displayed in the 12-hour format by default.
Example 6: Custom Time Zone (UTC, 24-Hour Format)
Output:
Explanation:
- This example displays the time in UTC with 24-hour format (using British English
en-GB
).
Summary:
date.toLocaleTimeString(locales, options)
is a useful method for formatting the time part of aDate
object.- You can customize the locales to format the time according to regional conventions, and the options object allows fine control over the display of hours, minutes, seconds, 12/24-hour format, and time zones.