Skip to content

JavaScript Date to a string using toString() Method

  • by

The JavaScript toString() method is used to convert the Date object to a string. It method returns the current day name, month name, date, year, and time.

Note: The toString() method is automatically called by JavaScript whenever a Date object needs to be displayed as a string.

Syntax

Date.toString()

Return value

It returns the converted string (representing the given date).

Convert JavaScript Date to string Example | toString() Method

The Example of toString() method converts a Date object to a string in JS.

<!DOCTYPE html> 
<html> 
    <body> 
        <script> 
        var d = new Date();
		var n = d.toString();

		alert(n);

        </script> 
    </body> 
</html> 

Output:

JavaScript Date to string Example toString Method

How to JavaScript date to string format?

Answer: You can do it:-

<script> 
        function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}

</script> 

Read more:- JavaScript date format example | code

Do comment if you have any suggestions, doubts or questions on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading