How to Display Current Date and Time Using JavaScript

Today we are going to learn how we can display current date and time using JavaScript. It might sound really tough. But in reality, this is a very easy program which anyone can use to find out the date and time, anytime you want.

HOW TO DISPLAY CURRENT DATE AND TIME IN JAVASCRIPT

The only thing that you need to keep in mind is how to use the predefined functions while writing the JavaScript code. For your convenience I will write both the HTML and the JAVASCRIPT codes below, first separately and then will give you the entire code, so that it is easy for you to understand.

HTML CODE

This is a simple HTML code which we use to display the current date and time.

<html>
<head>
<title>Date and Time.</title>
<body onLoad='getDate()' style="text-align: center">
    <h1>Current Date and Time:</h1>
    
    <h2 id="Date"></h2>
</body>

</html>

JAVASCRIPT CODE

In this example current Date and Time will display in H2 tag using¬† the function document.getElementById(“showDate”).innerHTML. We define a function, getCurrentDate for our purpose.

<script type="text/javascript">
      function getDate(){
        var cDate=new Date();
        document.getElementById("Date").innerHTML = cDate.toString();
      }
    </script>

 

Now we have to insert this JavaScript code in the body tag of the above HTML code.

<html>
  <head>
    <title>Date and Time.</title>
    <script type="text/javascript">
      function getDate(){
        var cDate=new Date();
        document.getElementById("Date").innerHTML = cDate.toString();
      }
    </script>
  </head>
<body onLoad='getDate()' style="text-align: center">
    <h1>Current Date and Time:</h1>
    
    <h2 id="Date"></h2>
</body>

</html>

 

OUTPUT

The sample output on 16th June 2019 at 12:31 is

Current Date and Time:

Sun Jun 16 2019 00:31:04 GMT+0530 (India Standard Time)

So you can see how easy and fun this code was. You can try out this example yours and may also read

 

Leave a Reply

Your email address will not be published. Required fields are marked *