Richard's JavaScript Tutorials

Updated 07/18/14

Home
Animation
precachedImages
digitalClock
Object Tag (Audio)
Cookies.htm
Math_Object
Using CSS
The Style Object
Client_Info
customObject
functions
UsingArrays
comments
concatenation
documentwrite
ifelse
Loops
forms
Strings
variables

 

Creating a JavaScript digital clock!

Here it is a running JavaScript digital clock. In this section we use the Date object to retrieve the current time and display it in a text box. 0's are added if the seconds or minutes is less than 10 and the time is formatted to a familiar format rather than the army format timing convention. The code is below the following script:

JavaScript Digital Clock

<html><head>
<title>JavaScript Digital Clock</title>
<script type="text/javascript">
<!--
function runningDigitalClock()
{

// Here the current date is grabbed to check if it is a morning or afternoon hour (AM or PM)
var digitalClock = new Date();
var timeAmPm = digitalClock.getHours();

if (timeAmPm >= 12)
{
timeAmPm = "PM";
}
else
{
timeAmPm = "AM";
}

//First, the hour is grabbed from the user's computer and examined.
//If the hour is 1 through 12 noon, nothing is done and it is
//allowed to display. If the hour is 13 through 23, it is
//changed into the more familiar 1 through 12 format and displayed.

var hours = digitalClock.getHours();
var newHours
if(hours > 12)
{
newHours = hours -12;
}
else
{
newHours = hours;
}

if (hours == 0)
{
newHours = "12";
}
else
{
newHours = newHours;
}
// In this part of the script there is a 0 added to keep the minutes column 2 spaces if minutes are less than 10
var newMinutes
var minutes = digitalClock.getMinutes();
if (minutes < 10)
{
newMinutes = "0" + minutes;
}
else
{
newMinutes = minutes;
}

// In this part of the script there is a 0 added to keep the seconds column 2 spaces if seconds are less than 10
var seconds = digitalClock.getSeconds() + 1;
var newSeconds, newMinuteSeconds;
if (seconds < 10)
{
newSeconds = "0" + seconds;
}
else
{
newSeconds = seconds}

if (newSeconds >= 60)
{
newMinuteSeconds = "00";
}
else
{
newMinuteSeconds = newSeconds;
}

// Here the timer is se this is where the clock starts ticking.
timer = setTimeout('runningDigitalClock()','1000');
var showClock = newHours + ":" + newMinutes +
":" + newMinuteSeconds + ":" + timeAmPm;
document.clock.clockface.value = showClock
}
//--></script></head>

<body  onLoad="runningDigitalClock()">
<FORM NAME="clock"><center>
<INPUT TYPE="text" name="clockface"></center></FORM></body></html>

 

For help with this or any other JavaScript on this website contact webmaster@cayemay.com

 

This site was last updated 07/08/14