Jack Nilan         Javascript Tutorial        EMail : jacknilan@yahoo.com



Lesson 3 - JavaScript - Printing Date and Time with Words



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

<script>
var day;
day = new Date();
</script>

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 monthname;
if (month == 0)
monthname = "January";
else
if (month ==1)
monthname = "February";
else
if (month ==2)
monthname = "March";
else if (month ==3)
monthname = "April";
else
if (month ==4)
monthname = "May";
else
if (month ==5)
monthname = "June";
else
if (month ==6)
monthname = "July";
else
if (month ==7)
monthname = "August";
else
if (month ==8)
monthname = "September";
else
if (month ==9)
monthname = "October";
else
if (month ==10)
monthname = "November";
else
if (month ==11)
monthname = "December";


You can write out the monthname using document.write()
document.write("The date is " + monthname + " " + dayofmonth + ", " + year);
</script>


Your assignment is to now get the day of the week printed out as a word. If you look above you will see that day2 is the variable that will receive the day of the week. But it is in number form. Like the get.Month() the getDay() function returns an integer. For Sunday it returns 0, for Monday a 1 etc. Write the code so that your day of the week can appear.