The Date Object, A JavaScript Clock

Time:
Date:

Here's the code

<HTML>
<HEAD>
</HEAD> <SCRIPT Language="JavaScript">
<!-- hide


// Declare the variables, Not totally necessary.
var timeStr, dateStr;
// Start of the function "clock". This function will be called up from inside the <BODY> tag latter.
function clock() {
// This statement creates a new Date-Object called now.
now= new Date();
// Now we give values to variables hours, minutes, and seconds by using the methods of object now.
// Note that you do not have to declare any variables before you use them.
hours= now.getHours();
minutes= now.getMinutes();
seconds= now.getSeconds();

// Next we put the hours, minutes, and seconds into a string called timeStr.
// First we set the value of the string to "", then add the hours to it.
timeStr= "" + hours;

// If the minutes or seconds are single digit numbers, we must pad them with a zero. Either way we must add a colon (:) to the string. The below is an if statement. It looks a little confusing because the seperator between the true and false values is also a colon (:).
timeStr+= ((minutes < 10) ? ":0" : ":") + minutes;
timeStr+= ((seconds < 10) ? ":0" : ":") + seconds;

// To display the time, we are putting the value of timestr into the field called time in the form called clock. This form is defined in the <body> of the HTML document.
document.form.name of first field.value=timestr
document.clock.time.value = timeStr;

// Date. Now we repeat the above putting the date, month, and year into a string called dateStr and putting it into the date field of the form clock.
date= now.getDate();
month= now.getMonth()+1;
year= now.getYear();
dateStr= "" + month;
dateStr+= ((date < 10) ? "/0" : "/") + date;
dateStr+= "/" + year;

document.form.name of second field.value=dateStr
document.clock.date.value = dateStr;
// The setTimeout is an Method of the window-Object. After 1000 msec. it calls up the function clock(). This also the end of the function
setTimeout("clock()",1000);
}

// -->
</script>
</HEAD>
// The fuction "clock" loads up as soon as the page is read in.
<BODY onLoad="clock()">
// The start of the form that is the clock's display. The top field is named time and the bottom field is named date.
<FORM NAME="clock">
Time:
<INPUT TYPE="text" NAME="time" SIZE="8" VALUE=""><br>
Date:
<INPUT TYPE="text" NAME="date"SIZE="8" VALUE="">
</FORM>

</BODY>
</HTML>



Retrun to JavaScript Index   Retrun to Home Page