Basics

Scripts

JS Links




































































































The HTML Writers Guild


Email Sunshine


Date/Time Functions

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.

dateVar = new Date();

This creates a variable called dateVar and initializes it to contain the curent date and time. If you want to initialize it with some other date and time, you can use any of the following alternate syntaxes.

dateVar = new Date("month day, year hours:minutes:seconds")
dateVar = new Date(year, month, day)
dateVar = new Date(year, month, day, hours, minutes, seconds)

Methods of the Date Object

The most commonly used methods of Date are given below. For a complete listing, refer to Netscape's JavaScript Documentation.

getYear()
dateVar.getYear() returns a number like 96 corresponding to the year of dateVar.
getMonth()
Returns a number between 0 and 11 corresponding to months January to December.
getDate()
Returns the day of the month.
getDay()
Returns a number specifying the day of the week. Zero is for Sunday, one for Monday and so on.
getHours()
Returns a number between 0 and 23 specifying the hour of day.

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 document.write() function. The following code does just that. You can insert it into an HTML file at the point you wish the greeting to appear.

<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 Clock

Here 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.

Back to Contents