JavaScript Date toString()
Syntax & Examples
Date.toString() method
The toString() method of the Date object in JavaScript returns a string representing the specified Date object. This method overrides the Object.prototype.toString() method.
Syntax of Date.toString()
The syntax of Date.toString() method is:
toString()
This toString() method of Date returns a string representing the specified Date object. Overrides the Object.prototype.toString() method.
Return Type
Date.toString() returns value of type String
.
✐ Examples
1 Using toString() to get the string representation of a Date object
In JavaScript, we can use the toString()
method to get the string representation of a Date object.
For example,
- We create a new Date object
date
representing January 1, 2000. - We use the
toString()
method to get the string representation of thedate
object. - The string is stored in the variable
dateString
. - We log
dateString
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date('2000-01-01T00:00:00Z');
const dateString = date.toString();
console.log(dateString);
Output
Sat Jan 01 2000 00:00:00 GMT+0000 (Coordinated Universal Time)
2 Using toString() with a specific date
We can use the toString()
method to get the string representation of a specific Date object.
For example,
- We create a new Date object
date
representing July 4, 1776. - We use the
toString()
method to get the string representation of thedate
object. - The string is stored in the variable
dateString
. - We log
dateString
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date('1776-07-04T00:00:00Z');
const dateString = date.toString();
console.log(dateString);
Output
Thu Jul 04 1776 00:00:00 GMT+0000 (Coordinated Universal Time)
3 Using toString() with the current date
We can use the toString()
method to get the string representation of the current date.
For example,
- We create a new Date object
date
representing the current date and time. - We use the
toString()
method to get the string representation of thedate
object. - The string is stored in the variable
dateString
. - We log
dateString
to the console usingconsole.log()
method.
JavaScript Program
const date = new Date();
const dateString = date.toString();
console.log(dateString);
Output
Depends on the current date and time (e.g., 'Mon May 27 2024 12:34:56 GMT+0000 (Coordinated Universal Time)')
Summary
In this JavaScript tutorial, we learned about toString() method of Date: the syntax and few working examples with output and detailed explanation for each example.