The above piece of information is brought to you by the following
JavaScript snippet:
var now = new Date();
document.write("Today's date
is: " + now + ".<BR>");
In this section of code var now = new Date() creates a
date object named now, which is then
printed with document.write().
Getting the Time via a Link
What time is it now?
(Move the mouse over the link several times and note that the date and
time stay the same as printed above.)
This example uses:
What time is it
<A
HREF="" onMouseOver="window.status='The
time is ' + now; return true;">
now
</A>?
NOTES:
- As above, the present date is gotten from now
= new Date(); but this happens only once, when the
page is loaded, so the value of now is
not updated.
- When you move the mouse over the link, the value of now
is displayed (but since this value is only defined once, the time is
not updated).
And what time is it now?
(Move the mouse over the link several times and note that here the time does
change.)
The JavaScript code in this case is:
function getTime() {
var now = new Date();
window.status
= 'The time is ' + now;
}
And what time is it
<A
HREF=""
onMouseOver="getTime();
return true;"
onMouseOut="status='';">
now
</A>?
NOTES:
- Moving the mouse over the "now" link causes the
user-defined function getTime()
to be called. This sets now = new
Date() to the current time and displays it on the status bar.
- Since getTime()
is called each time the mouse is placed over the "now"
link, the now variable is updated each
time. Consequently the present date and time are shown.
You can extract parts of a date object by using its various methods.
The following methods return the indicated date parts:
- getDay() --
day of the week (a number between 0 -- 6)
- getMonth() --
month of the year (a number between 0 -- 11)
- getDate() --
day of the month (a number between 1 -- 31)
- getHours() --
hour of the day (a number between 0 --23)
- getMinutes() --
minutes after the hour (a number between 0 --59)
- getSeconds() --
(a number between 0 --59)
- getYear() --
the last two digits of the year
- getFullYear() --
get the full 4 digits of the year
Finally, you can even have JavaScript add a digital clock or a
calendar to your page. Several of these types of examples will be
covered next week. |