JavaScript Date toString() Method



The JavaScript Date.toString() method is used to convert a Date object to a string. The return value will be a string that represents the date, time, and timizone according to the local timezone.

For primitive values such as numbers, booleans, and strings, toString() returns the primitive value converted to a string. If the Date object is "invalid", this method returns "invalid date" as result. For null and undefined, toString() returns the string representations of "null" and "undefined", respectively.

Syntax

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

toString();

This method does not accept any parameters.

Return Value

This method returns Date and Time represented as a string.

Example 1

In the following example, we are demonstrating the basic usage of JavaScript date toString() method −

<html>
<body>
<script>
   const currentDate = new Date();
   const dateString = currentDate.toString();

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

Output

The above program returns the date object as a string.

Example 2

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

<html>
<body>
<script>
   const specificDate = new Date('2023-12-26 06:30:00');
   const dateString = specificDate.toString();

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

Output

It converts and return the date 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('2023-15-56 06:30:00');
   const dateString = specificDate.toString();

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

Output

The program returns "invalid date" as a result.

Advertisements