Javascript Clock

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


In this snippet, we will go through javascript code of a javscript clock that shows the current client time without requiring the user to reload the page.

Javascript Clock Demo

Javascript Clock Code

  <script language="javaScript">
  function checklength(i){
         if (i<10){
          i="0"+i;}
          return i;
  }
  function clock(){
    var now = new Date();
    var hours = checklength(now.getHours());
    var minutes = checklength(now.getMinutes());
    var seconds = checklength(now.getSeconds());
    var format = 1;  //0=24 hour format, 1=12 hour format
    var time;
 
    if (format == 1){
      if (hours >= 12){
        if (hours ==12){
          hours = 12;
        }else {
          hours = hours-12;
        }
       time=hours+':'+minutes+':'+seconds+' PM';
      }else if(hours < 12){
           if (hours ==0){
             hours=12;
           }
       time=hours+':'+minutes+':'+seconds+' AM';
      }
    }
   if (format == 0){
      time= hours+':'+minutes+':'+seconds;
   }
 
   document.getElementById("clock").innerHTML=time;
   setTimeout("clock();", 500);
  }
 
 </script>

Declare the above javascript clock function in the head of the page.

Now, use the javascript clock within the div id ("clock") below where ever you want to show the clock.

<div id="clock"> 
<script language="javascript">
<!--
 clock();
 //-->
 </script>
</div>





8 points

That's not server time: that's client time. Remember JavaScript is run in the browser.

Anonymous's picture
Created by Anonymous
4 points

This is correct. It is client time and not server time. I have fixed it in the post above.

Anonymous's picture
Created by Anonymous
13 points

Also, you are only supposed to use an element ID once per page, or it stops being valid. You should use a class instead if you might want to use it in more than one place.

Anonymous's picture
Created by Anonymous
2 points

What exactly is the main difference concerning the iphone4 and new iphone 5 which are coming out for America?
i'd like to find out should it be worth it to obtain the iphone 4 or if i should just wait for new iphone 5.

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.