JavaScript toLocaleTimeString(): Get the time as a string using locale conventions

The JavaScript toLocaleTimeString() method is used to get the time (using the locale conventions) as a string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      const d = new Date();
      let timeLocale = d.toLocaleTimeString();
      document.getElementById("xyz").innerHTML = timeLocale;
   </script>

</body>
</html>
Output

When the page is loaded, the JavaScript code creates a new Date object representing the current date and time. It then calls the toLocaleTimeString() method on this object to get the local time string representation of the current date and time.

The toLocaleTimeString() method returns a string representing the time portion of the date in a localized format. The format of the string returned by this method depends on the locale settings of the user's system.

Finally, the code sets the inner HTML of a p element with the id attribute "xyz" to the local time string representation obtained from the toLocaleTimeString() method.

JavaScript toLocaleTimeString() Syntax

The syntax of the toLocaleTimeString() method in JavaScript is:

x.toLocaleTimeString()

where x must be an object of the Date() constructor.

The toLocaleTimeString() method returns a string, which will be the time using the locale conventions.

Please note: To get the date using local conventions, use toLocaleDateString().

Please note: To get the complete date using local conventions, use toLocaleString().

Please note: To display the date in the format dd-mm-yyyy, refer to its separate example.

Please note: To display time in the format hh:mm:ss, refer to its separate example.

Please note: To display time in the format hh:mm:ss AM/PM, refer to its separate example.

Advantages of the toLocaleTimeString() method in JavaScript

Disadvantages of the toLocaleTimeString() method in JavaScript

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!