How to Display the Date in HTML Using JavaScript?

Estimated read time 2 min read

Displaying the date in HTML using JavaScript can be done by using the Date object in JavaScript and inserting the resulting date string into the HTML document using innerHTML property or textContent property.

Here’s an example of how to display the current date in an HTML element with an id of “date”:

<!DOCTYPE html>
<html>
  <head>
    <title>My Website</title>
  </head>
  <body>
    <p id="date"></p>
    <script>
      let date = new Date();
      let dateElement = document.getElementById("date");
      dateElement.textContent = date.toDateString();
    </script>
  </body>
</html>

In this example, we first create a Date object to represent the current date and time. We then use JavaScript to select an HTML element with an id of “date” and insert the date string obtained using the toDateString method of the Date object into the text content of the element.

You can format the date string in various ways using the various methods of the Date object. For example, you can use toLocaleDateString method or toUTCString method to display the date in a localized format or in UTC time, respectively.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply