Building a JavaScript digital clock

This example will show you to build digital clock in JavaScript. To create the clock, we will use three JavaScript methods: getHours () to get the hour, getMinutes () to get minutes, and getSeconds () to get seconds. See the code below for details.

The following shows the output of the script code shown below:

digital clock

Scripting code

Step 1: place the following JavaScript code in the head section (between <head> and </head>) of your web document.

<script language="javascript">
<!--
function DisplayTime () {
dateObj = new Date();
// get hours
var hour = dateObj.getHours();
// get minutes
var minutes = dateObj.getMinutes();
// get seconds
var seconds = dateObj.getSeconds();
// is hour less then 10?
if (hour < 10) {
// add 0 in front so the hour become, for example, 01 instead of 1
// we do this to always display two digits for the hour
hour = "0" + hour;
}
// is minutes less then 10?
if (minutes < 10) {
// add 0 in front so the minutes become, for example, 01 instead of 1
// we do this to always display two digits for the minutes
minutes = "0" + minutes;
}
// is seconds less then 10?
if (seconds < 10) {
// add 0 in front so the seconds become, for example, 01 instead of 1
// we do this to always display two digits for the seconds
seconds = "0" + seconds;
}
// now add our hour, minutes, and seconds to the input box
document.clock.time.value = hour + ":" + minutes + ":" + seconds;
// we continuously call the DisplayTime () funtion after 1000 milliseconds
// or after 1 second. Basically, this will change the time in our clock.
// For example, you would observe the seconds being changed every second.
// In other words, this script will continue to execute every one second!
setTimeout("DisplayTime()", 1000);
}
//-->
</script>

Step 1.1: place also the following styling code before <script> tag or after </script> tag, if any, but in the head section (between <head> and </head>) of your web document.

<style>
/* defining styles for our clock through a class called TimeBox */
.TimeBox {
border:#0083C1 1px solid;/* border color, size, and type */
font-size:10pt;/* font size to use*/
background-color:#0083C1;/* background color of the time/input box */
color:#FFFFFF;/* font color*/
font-family:"Courier New", Courier, monospace;/* type of font*/
text-align:center;/* align our time to the center*/
font-weight:bold;/* display time bold-type */
}
</style>

Step 2: Place the following code in your web page:

<form name="clock">
<table width="80" border="0" cellspacing="0" cellpadding="2">
<tr align="center">
<td>
<input type="text" name="time" size="8" class="TimeBox" />
<script language="javascript">
DisplayTime ();
</script>
</td>
</tr>
</table>
</form>