How to display the current date in a webpage using JavaScript
In this post we will give you information about How to display the current date in a webpage using JavaScript. Hear we will give you detail about How to display the current date in a webpage using JavaScriptAnd how to use it also give you demo for it if it is necessary.
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 (/) separatorconst 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.
Hope this code and post will helped you for implement How to display the current date in a webpage using JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs