Current Date

You can use JavaScript to determine the current date and time and post it on your web page.

Click here for an example

To do this you will need to write to scripts, one in the head portion of your webpage (a header script) and one in the body (a body script). We will start by adding a script to the head.

<script language = "javascript" type="text/javascript">

</script>

Inside the script you must define two new arrays. The first array will contain the names of the days of the week and the second array will contain the months of the year. Make sure that you put the days and months in the correct order if you want to get the right date. You also need to add the line now = new Date. JavaScript will create a new date object and put the current date into it.

<script language = "javascript" type="text/javascript">

dayName = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
monName = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")

now = new Date

</script>

Now we are done with the header script. To create the body script you will once again add the javascript tags.

<script language = "javascript" type="text/javascript">

</script>

Inside the script you will add code indicating what to display in the browser window.

<script language = "javascript" type="text/javascript">

document.write("The current date is " + dayName[now.getDay()]+", "+monName[now.getMonth()]+" "+now.getDate() + ".")

</script>

The document.write command tells the browser to display what follows it. The now.getDay gets the day from the now object that we created in the header script. It will return a numerical value between 0 and 6 which will represent the day of the week. The dayName[now.getDay()] command uses the dayName array that we created in the header script to display the correct name of the day. If now.getDay() returns the number 0, it will display the first element of the array (Sunday). If it returns three, it will display the forth element of the array (Wednesday). The monName[now.getMonth()] command displays the correct month using the monName array. The now.getDate() displays the numerical value of the date.

Here is the code for the example:

<html>
<head>
<title>Date</title>

<script language = "javascript" type="text/javascript">

dayName = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
monName = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")

now = new Date

</script>

</head>

<body>

<script language = "javascript" type="text/javascript">

document.write("The current date is " + dayName[now.getDay()] + ", " + monName[now.getMonth()] + " " + now.getDate() + ".")

</script>

</body>
</html>