JavaScript toDateString() | Get Date as String

The JavaScript toDateString() method is used to get the date as a string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p id="xyz"></p>

   <script>
      const d = new Date();
      let currentDate = d.toDateString();
      document.getElementById("xyz").innerHTML = currentDate;
   </script>

</body>
</html>
Output

JavaScript toDateString() Syntax

The syntax of toDateString() method in JavaScript is:

x.toDateString()

where x must be an object of the Date() constructor.

The toDateString() method returns a string representing the current date.

Print Date Separately in JavaScript using toDateString()

Since the toDateString() method returns the complete date as a string that contains the name of the weekday, month name, date, and year. Therefore we can use the slice() method to slice the value from the string to print the value separately. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>
   
   <p>Date: <span id="day"></span></p>
   <p>Month: <span id="month"></span></p>
   <p>Year: <span id="year"></span></p>

   <script>
      const d = new Date();
      let currentDate = d.toDateString();
      document.getElementById("day").innerHTML = currentDate.slice(8, 10);
      document.getElementById("month").innerHTML = currentDate.slice(4, 7);
      document.getElementById("year").innerHTML = currentDate.slice(11);
   </script>

</body>
</html>
Output

Date:

Month:

Year:

Please note: To display date in format dd-mm-yyyy, refer to its separate example.

Please note: To display time in format hh:mm:ss, refer to its separate example.

Please note: To display time in format hh:mm:ss AM/PM, refer to its separate example.

JavaScript Online Test


« Previous Tutorial Next Tutorial »