• JavaScript Video Tutorials

JavaScript Date toLocaleTimeString() Method



The Date.toLocaleTimeString() method in JavaScript is used to convert a Date object to a string representing the time portion of the date according to the locale-specific time formatting.

Syntax

Following is the syntax of JavaScript Date toLocaleTimeString() method −

toLocaleTimeString(locales, options);

Parameters

This method accepts two parameters. The same are described below −

  • locales (optional) − This is an optional parameter representing a string with a BCP 47 language tag or an array of such strings. It specifies the locale or locales to be used. If this argument is not provided or is undefined, the default locale of the JavaScript runtime is used.
  • options (optional) − An optional parameter representing an object with properties that customize the output. These properties include −
    • timezone Specifies the time zone to use. The default is the runtime's default time zone.
    • hour12 A Boolean indicating whether to use 12-hour time format (true) or 24-hour time format (false). Default is the runtime's default setting.
    • hour A string with values like "numeric", "2-digit", or undefined.
    • minute A string with values like "numeric", "2-digit", or undefined.
    • second A string with values like "numeric", "2-digit", or undefined.
    • timeZoneName A string with values like "short", "long", or undefined.

Return Value

This method returns the time portion of a date object as a string according to current locale's conventions.

Example 1

The following example uses JavaScript Date toLocaleTimeString() method to return the time portion of a date in the user's local time zone −

<html>
<body>
<script>
   const date = new Date();
   const timeString = date.toLocaleTimeString();

   document.write(timeString);
</script>
</body>
</html>

Output

As we can see in the output, it returned the time portion of a Date object.

Example 2

In this example, we are using the "options" parameter to customize the output. The hour and minute options are set to display the time in a two-digit format.

<html>
<body>
<script>
   const date = new Date();
   const options = { hour: '2-digit', minute: '2-digit' };
   const timeString = date.toLocaleTimeString(undefined, options);

   document.write(timeString);
</script>
</body>
</html>

Output

As we can see in the output, the hour and minute are displying in two-digit format.

Example 3

Here, the hour12 option is set to false, which means the time will be displayed in 24-hour format (0-23) instead of the default 12-hour format with AM/PM.

<html>
<body>
<script>
   const date = new Date();
   const options = { hour12: false };
   const timeString = date.toLocaleTimeString(undefined, options);

   document.write(timeString);
</script>
</body>
</html>

Output

If we execute the program, it displays the time in 24 hour format along with AM/PM.

Advertisements