Javascript Clock



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>





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

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

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.

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.