A date object is created by the new operator. We have not seen this operator uptil now. But its not difficult to comprehend. When you want to create a new date object, you can use:
myDate = new Date();
Note that the case is important. The correct spelling of Date start with a capital D. You can next display the date using:
Following is a simple code that displays a textbox alongwith an associated button. When you click the button, the contents of the new Date() appear in the textbox.
When the date will be displayed it will have the form “Sat Apr 23 17:43:31 UTC+0500 1994“. (Don’t worry about the year; my computer clock has been set to 1994). As you can see you may want to reformat this informat. There are ways of extracting year, month, hour, etc. from this object. There is one other important thing: this date is of the computer where the web page will be displayed (not where the web page resides).
Associate Properties and Methods
We can summarize the methods available with the date object in the following table. Their use will be explained in the next section, i.e. Creatively Using the Date.
Date() Returns a new date object
getDate() Returns a date from the date object (0-31)
getDay() Returns the day of the week (0-6)
getMonth() Returns the month (0-11)
getFullYear() Returns the year (2000)
getHours() Returns the hour (0-23)
getMinutes() Returns the minute (0-59)
getSeconds() Returns the seconds (0-59)
Creatively Using the Date
We will now do a simple example that will explain how we can display time on a web page. To understand the code you should have concepts of setTimeOut(). It was explained in my last article; go there if you don’t have the concept and have difficulty in comprehending the following code.
First of all, we declare that the function showDate will time out after every 1 second. The function actually displays the current time. And since it is called after every second; the time displayed is continuously updated. The function puts the getHours(), getMinutes() and getSeconds() all into the textbox, named dateBox.
The value of the string text is built in steps. First the hours are added to the empty string; then a colon; then minutes; then again a colon; and then the seconds. Copy and paste this example into a file; save it and open into your browser to see how it works.