Javascript show clock in webpage example

This example show how to insert clock on the website which is not static clock, but like a digital clock.

Script for Creating Clock

1:   <script type="text/javascript">  
2:      function updateClock() {  
3:        var currentTime = new Date();  
4:        var currentHours = currentTime.getHours();  
5:        var currentMinutes = currentTime.getMinutes();  
6:        var currentSeconds = currentTime.getSeconds();  
7:        // Pad the minutes and seconds with leading zeros, if required  
8:        currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;  
9:        currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;  
10:        // Choose either "AM" or "PM" as appropriate  
11:        var timeOfDay = (currentHours < 12) ? "AM" : "PM";  
12:        // Convert the hours component to 12-hour format if needed  
13:        currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;  
14:        // Convert an hours component of "0" to "12"  
15:        currentHours = (currentHours == 0) ? 12 : currentHours;  
16:        // Compose the string for display  
17:        var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;  
18:        // Update the time display  
19:        document.getElementById("clock").firstChild.nodeValue = currentTimeString;  
20:        //return currentTimeString;  
21:      }  
22:    </script>  

Call the clock on body load

1:  <body onload="updateClock(); setInterval('updateClock()', 1000 );">  

Div element for clock

1:   <div id="clock" style="font-size:larger; font-family:Verdana;">  
2:    </div>  

Output


Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

How to create DataGrid or GridView in JSP - Servlet

Control Webpart Visible/Enable using macro in Kentico