Before we go through the tutorial of Display Current Date and Time in HTML using JavaScript, we have to know the brief of JavaScript and Date method in JS.
Scroll to bottom, to check live view
Introduction
JavaScript is light-weight a client-side scripting language used to build client-side validations and much more. Today we use it for display current date and time in the HTML input box.
We use JavaScript Date object to get current date and time.

Creating JS Date Object
JavaScript date object help to getting the current date and time which we also used for getting the visitors current time and date to store on database also.
1 2 3 |
<script> var today = new Date(); </script> |
Use Get Method to Display Current Date in JavaScript
Use the below source code to display the current date in the HTML input box using JavaScript in the “Y-m-d” format.
1 2 3 4 5 6 7 8 |
Current Date: <input type="text" id="currentDate"> <script> var today = new Date(); var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate(); document.getElementById("currentDate").value = date; </script> |
Explanation:
- getFullYear() – Get current year like 2020.
- getMonth() – Get current month values 0-11. Where 0 for Jan and 11 for Dec. So added +1 to get result.
- getDate() – Get day of the month values 1-31.
Use Get Method to Display Current Time in JavaScript
We use same get method to display current time and also display it on the HTML text box.
Format “H:i:s“
1 2 3 4 5 6 7 8 |
Current Time: <input type="text" id="currentTime"> <script> var today = new Date(); var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); document.getElementById("currentTime").value = time; </script> |
Explanation:
- getHours() – Get current hour between 0-23.
- getMinutes() – Get current minutes between 0-59.
- getSeconds() – Get current seconds between 0-59.
Display Both Current Date and Time in HTML using JavaScript
See the Pen Get Current Date and Time Using JS by Bikash Panda (@phpcodertech) on CodePen.
Above is the complete explanation of source code of Display Current Date and Time in HTML using JavaScript.
Also Check:
- DOM | DOCUMENT OBJECT MODEL
- SELECTION IN CSS | CSS ::SELECTION
- 3D LOADER USING CSS
- PERCENTAGE DIFFERENCE CALCULATOR USING JQUERY & PHP
Happy Coding..!
Pingback: Git Command to Get the Latest Code From Master - PHPCODER.TECH
Pingback: Get Number of Days Between Two Dates using JS - PHPCODER.TECH
Pingback: Increase PHPMyAdmin Import Size Ubuntu & XAMPP-PHPCODER.TECH