The toTimeString method in JavaScript is utilized to obtain the time segment of a Date object, returning it as a string format.
Syntax
The syntax for the toTimeString method is expressed as follows:
Example
dateObj.toTimeString()
Return
A string that denotes the time component of a Date object.
JavaScript Date toTimeString method example
In this section, we will explore the toTimeString method by examining multiple examples.
Example 1
Let’s examine an illustration that demonstrates how to obtain the current time as a string.
Example
<script>
var time=new Date();
document.writeln(time.toTimeString());
</script>
Output:
Output
10:19:29 GMT+0530 (India Standard Time)
Example 2
Let’s examine an example that retrieves only the time component from a given Date object.
Example
<script>
var time=new Date("August 15, 1947 20:22:10 GMT+0530 (India Standard Time) ");
document.writeln(time.toTimeString());
</script>
Output:
Output
20:22:10 GMT+0530 (India Standard Time)
Example 3
Let's examine another instance in which we can extract only the time segment from a designated Date object.
Example
<script>
var time=new Date(1947, 7, 15, 20, 22, 10);
document.writeln(time.toTimeString());
</script>
Output:
Output
20:22:10 GMT+0530 (India Standard Time)