by Sai gowtham

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:

  1. Add the following code to your html.
<div>
   <p id="date"></p>
</div>
  1. 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:

displaying the date in html using JavaScript

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.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course