65.9K
CodeProject is changing. Read more.
Home

Good one and simple example for beginners to display time on browser using java script

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.50/5 (6 votes)

Sep 30, 2005

viewsIcon

24520

downloadIcon

212

The code demonstrates displaying time using javascript.The javascript function showtime will be called onLoad event of form body tag.settTimeout will keep on dispalying the time for set interval.

Sample Image - JavascriptTime.jpg

Introduction

<script language="javascript">
   function showTime()
   {
    now=new Date();
    var hour=now.getHours();
    var min=now.getMinutes();
    var sec=now.getSeconds();

    if (min<=9) { min="0"+min; }
    if (sec<=9) { sec="0"+sec; }
    if (hour<10) { hour="0"+hour; }  
      
       
    if (hour>12)
     { hour1= hour - 12;}
    else
     hour1 = hour;
    if (hour1<10) { hour1="0"+hour1; } 
    
    var ctime =  hour1 + ":" + min + ":" + sec;
    LABEL1.innerText= ctime;
    setTimeout("showTime()", 1000);
   }
  </script>

 

The above code diplayes the time in a label control named LABEL1.
you can create a simple html page and add a label and name it LABEL1.
Then add the above script into header section of the html.
Try accessing the page. You can also down load the sample code.