JavaScript Date toTimeString()
Syntax & Examples
Date.toTimeString() method
The toTimeString() method of the Date object in JavaScript returns the time portion of the Date as a human-readable string. This string includes the hours, minutes, seconds, and time zone information.
Syntax of Date.toTimeString()
The syntax of Date.toTimeString() method is:
toTimeString()
This toTimeString() method of Date returns the "time" portion of the Date as a human-readable string.
Return Type
Date.toTimeString() returns value of type String
.
✐ Examples
1 Using toTimeString() to get the time portion of a Date object
In JavaScript, we can use the toTimeString()
method to get the time portion of a Date object as a human-readable string.
For example,
- We create a new Date object
date
representing January 1, 2000. - We use the
toTimeString()
method to get the time portion of thedate
object. - The time string is stored in the variable
timeString
. - We log
timeString
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date('2000-01-01T00:00:00Z');
const timeString = date.toTimeString();
console.log(timeString);
Output
00:00:00 GMT+0000 (Coordinated Universal Time)
2 Using toTimeString() with a specific date
We can use the toTimeString()
method to get the time portion of a specific Date object.
For example,
- We create a new Date object
date
representing July 4, 1776. - We use the
toTimeString()
method to get the time portion of thedate
object. - The time string is stored in the variable
timeString
. - We log
timeString
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date('1776-07-04T00:00:00Z');
const timeString = date.toTimeString();
console.log(timeString);
Output
00:00:00 GMT+0000 (Coordinated Universal Time)
3 Using toTimeString() with the current date
We can use the toTimeString()
method to get the time portion of the current date.
For example,
- We create a new Date object
date
representing the current date and time. - We use the
toTimeString()
method to get the time portion of thedate
object. - The time string is stored in the variable
timeString
. - We log
timeString
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date();
const timeString = date.toTimeString();
console.log(timeString);
Output
Depends on the current time (e.g., '12:34:56 GMT+0000 (Coordinated Universal Time)')
Summary
In this JavaScript tutorial, we learned about toTimeString() method of Date: the syntax and few working examples with output and detailed explanation for each example.