Jack Nilan         Javascript Tutorial        EMail : jacknilan@yahoo.com

Lesson 2 - JavaScript - Printing Date and Time

The Date object works with the built in computer clock. The date and time can be stored in a variable.

To declare a variable you use keyword var (inside of script).

var day;
day = new Date();

Variable day now holds the exact date and time when the statement was executed. We can now get the information that is stored in the Date object.

We can get the information calling the "methods" of the date object.

var milli = day.getTime(); // returns milliseconds that have elapsed since 1/1/70
var year = day.getFullYear(); // returns the Year
var month = day.getMonth(); // returns the month (0-11 January = 0)
var dayofmonth = day.getDate(); // returns the day of the month
var day2 = day.getDay(); // returns the integer day of the week (Sunday = 0)
var hour = day.getHours(); // returns the integer hour (0 -> 23)
var minute = day.getMinutes(); // returns the Minute (0 - > 59)
var second = day.getSeconds(); // returns the Second (0 -> 59)

You can write out the date or time using document.write()
document.write("The date is " + (month + 1) + "/" + dayofmonth + "/" + year);
Which would print out :

then you can end your script


Note how the + sign can be used so we can print out strings (things in quotation marks and variables. If we put everything inside quotes it would come out exactly like that. Variables do not go inside quotes.

Lesson 2 Continued