|
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 current 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.
A Digital Clock
Here is a clock program written in JavaScript.
The source code for it is given below.
The setTimeout() function is discussed in more detail on
the Scroller page. The blur()
method is used to remove focus from the Clock textbox.
Placing
Dates on the page:
This script isn't placed between the <HEAD></HEAD> Codes.
Use the code below and the date will be placed wherever the script is
placed.
|