Introduction To Javascript
The Date Object

How would you get date information?

var now = new Date()

The above line defines the variable now as a new date object based on the current date and time. To get the hour of the day you would enter,

var h = now.getHours()

The table below lists the other information that you can extract about the date.

now.getHours() The hour of the day in 24 hour clock format.
now.getMinutes() The minutes of the current date.
now.getSeconds() The seconds of the current date.
now.getDay() Gives the day of the week as a number from 0 to 6. (0 = Sunday)
now.getMonth() Gives the month as a number from 0 to 11. (0 = January)

Clock Script

The clock script uses the built-in Date() object in Javascript to create a ticking clock. The setTimeout() statement runs the function once every millisecond.

Use this code in the body of your page to recreate the clock - use some CSS to format it nicely. You will have to create a form in the body of the page called, clock and an input box called clocky.

function dotime() {
var now = new Date()
var h = now.getHours()
var m = now.getMinutes()
var s = now.getSeconds()
if (h<10) h="0" + h
if (m<10) m="0" + m
if (s<10) s="0" + s
var tim = h + ":" + m + ":" + s
document.clock.clocky.value = tim
var doagain= setTimeout("dotime()",1)
}
dotime()

Other Uses of Dates

You do not have to use the current time for your date objects. Suppose you defined your date object as,

var then = new Date(2001,3,24)

The variable then is a date object for the date specified. You can redefine the properties of the date with the following statements.

then.setHours() Sets the hour of the day in 24 hour clock format.
then.setMinutes() Sets the minutes of the date.
then.setSeconds() Sets the seconds of the date.
then.setDay() Sets the day of the week as a number from 0 to 6. (0 = Sunday)
then.setMonth() Sets the month as a number from 0 to 11. (0 = January)