Finding date and time – A simple clock in JavaScript

Finding date and time – A simple clock in JavaScript cover image
  1. Home
  2. JavaScript
  3. Finding date and time – A simple clock in JavaScript

It is easy to find the time and date on the visitor’s computer (client side) using the JavaScript Date object with its various methods. Let’s construct a simple function that finds the time (hours:minutes:seconds) and prints it in the document.

<script type="text/javascript">
<!--
function det_time()
   {
   var d = new Date();
   var c_hour = d.getHours();
   var c_min = d.getMinutes();
   var c_sec = d.getSeconds();
   var t = c_hour + ":" + c_min + ":" + c_sec;
   return t;
   }
//-->
</script>

When we call this function it prints the time as follows:

In order to keep the clock ticking, as it were, we would have to call det_time() function again and again. JavaScript provides an method called setInterval() that takes two arguments; the first is the function that has to be called repeatedly and the second, the time interval (in milliseconds). In our case, the clock has to be called every second (1000 milliseconds).

setInterval("det_time()", 1000);

Lastly, for correct execution, its best to put this clock inside a text field.

Click here to see how this works!

Here is the complete code:

//This function is placed in the HTML head section
function det_time()
   {
   var d = new Date();
   var c_hour = d.getHours();
   var c_min = d.getMinutes();
   var c_sec = d.getSeconds();
   var t = c_hour + ":" + c_min + ":" + c_sec;
   document.myform.my_time.value = t;
   }


//The following code is placed in the HTML body...
<form name="myform">
<input type="text" size="10" maxlength="10" value="" 
name="my_time">
</form>
<script type="text/javascript">
<!--

setInterval("det_time()", 1000);

//-->
</script>

JavaScript