• JavaScript Video Tutorials

JavaScript Date toTimeString() Method



The Date.toTimeString() method in JavaScript is used to convert a Date object to a string representing the time portion of the date in the local time zone.

It returns a string representing the time portion of the Date object in the format "HH:MM:SS GMTOffset", where HH represents the hour (24-hour clock), MM represents the minutes, SS represents the seconds, and GMTOffset represents the local time zone offset from GMT in the format +HHMM or -HHMM.

If the provided Date object is "invalid", this method returns "invalid date" as result.

Syntax

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

toTimeString();

This method does not accept any parameters.

Return Value

A string representing the time portion of the Date object in the local time zone.

Example 1

Following is the basic usage of JavaScript Date toTimeString() method −

<html>
<body>
<script>
   const currentDate = new Date();
   const timeString = currentDate.toTimeString();

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

Output

The above program returns time portion of the date object as string.

Example 2

In the below example, we provided a specific date and time (December 26, 2023 12:30:00) to the date object −

<html>
<body>
<script>
   const specificDate = new Date('December 26, 2023 12:30:00');
   const timeString = specificDate.toTimeString();

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

Output

It converts and return the time portion of the date object as a string.

Example 3

Here, the date object is created with an invalid date i.e. the date and time values that are outside the valid range.

<html>
<body>
<script>
   const specificDate = new Date('December 26, 2023 34:90:00');
   const timeString = specificDate.toTimeString();

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

Output

The program returns "invalid date" as a result.

Advertisements