How to find and display client side time and date using simple JavaScript built in clock functions such as setinterval method.
finding date and time - a simple clock in JavaScript, javascript setinterval method, setinterval() javascript method, client side time and date
Finding date and time - A simple clock in JavaScriptGo to Finding date and time - A simple clock in JavaScriptHTML & JavaScriptGo to HTML and JavaScript tips and tricksTips and tricksGo to web development Tips and tricksHomepage

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 LANGUAGE="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.

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 LANGUAGE="JAVASCRIPT">
<!--

setInterval("det_time()", 1000);

//-->
</SCRIPT>


AddThis Social Bookmark Button


Page contents: Learn how to display date and time on a visitors browser using JavaScript code and thus create a simple JavaScript clock with the setinterval javascript method.

Page URL: http://www.webdevelopersnotes.com/tips/html/ finding_date_and_time_a_simple_clock_in_javascript.php3



Join Mailing List


Feedback/Questions




50+ web hosting FAQs

Search engine for your website

Free software from Google - The Google Pack Collection

Create your own search engine
Search WebDevelopersNotes.com