|
To make it easy to handle date and time, JavaScript has
a built in Date object. A Date
variable has to be created explicitly before we can
use it. This can be done using the following JavaScript
statement.
This creates a variable called
Methods of the Date ObjectThe most commonly used methods ofDate are
given below. For a complete listing, refer to
Netscape's JavaScript Documentation.
You might have come across sites that wish you a
Good morning or a Good evening depending
on the time you visit it. This can be achieved by
checking the current time and inserting the appropriate
greeting using the
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this code from non JavaScript browsers
currentTime = new Date();
if (currentTime.getHours() < 12)
document.write("Good morning");
else if (currentTime.getHours() < 17)
document.write("Good afternoon");
else
document.write("Good evening");
// End of JavaScript code -->
</SCRIPT>
A Digital ClockHere is a clock program written in JavaScript.
The source code for it is given below.
<TABLE BORDER=4 BGCOLOR=CYAN>
<TR><TD>
<FORM NAME="clock_form">
<INPUT TYPE=TEXT NAME="clock" SIZE=25>
</FORM>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from non JavaScript browsers
function clockTick()
{
currentTime = new Date();
document.clock_form.clock.value = " "+currentTime;
document.clock_form.clock.blur();
setTimeout("clockTick()", 1000);
}
clockTick();
// End of clock -->
</SCRIPT>
</TD></TR>
</TABLE>
The setTimeout() function is discussed in
more detail on the Scroller
page. The blur() method is used to
remove focus from the Clock textbox. |