How to display the current date in a webpage using JavaScript
In this tutorial, we are going to learn about how to display the current date in the HTML webpage with the help of JavaScript.
Using the new Date() constructor
JavaScript has a built-in new Date()
constructor, which contains a toDateString()
method that gets the date in a string format according to the user local time.
Example:
- Add the following code to your html.
<div>
<p id="date"></p>
</div>
- Now, add the following code to your JavaScript.
const el = document.getElementById('date');
const dateString = new Date().toDateString();
el.textContent = dateString; // passing the date to html element
It displays the date similar to the below image in your webpage:
or
We can also construct the date in our own format by using the following methods:
getDate() : It returns the day of the month.
getMonth(): It returns the month of a year, where 0 is January and 11 is December.
getFullYear() : It returns the year in four-digit format (YYYY).
Here is an example:
<div>
<p id="date"></p>
</div>
const el = document.getElementById('date');
const current= new Date();
const day = current.getDate();
const month = current.getMonth()+1;
const year = current.getFullYear();
// it returns the final date with backslash (/) separator
const date = `${day}/${month}/${year}`;
el.textContent = date;
Output:
27/8/2020
You can also replace the backslash(/
) separator with dashes (-
) or even interchange the day or month or year, according to your needs.