Print this Section


The Date Object

The Date object contains several methods (it has no properties) to permit you to work with date and time settings taken from the system clock of the user's PC. Before working with dates and times you need to create a new instance of the JavaScript Date object by assigning it to a variable.

var date = new Date()

Figure 2-28. General format to create a Date object.

This statement gets the current date and time from the system clock and stores it in the variable. Then you can reference date and time methods associated with this variable.

The following statement creates a Date object named TheDate. It is used in the following table which lists methods associated with this object. The values shown were taken from your computer's clock when this page was loaded.

var TheDate = new Date();
Method Description Returns
getDate() Returns the day of the month.
getDay() Returns the numeric day of the week (Sunday = 0).
getMonth() Returns the numeric month of the year (January = 0).
Returns the current year.

getTime() Returns the number of milliseconds since January 1, 1970.
getHours() Returns the military hour of the day.
getMinutes() Returns the minute of the hour.
getSeconds() Returns the seconds of the minute.
getMilliseconds() Returns the milliseconds of the second.

Figure 2-29. Methods of the Date object.

The above date and time formats are appropriate for performing calculations with their numeric equivalents. There are several string methods, though, that can be applied to dates and times for display purposes. These methods are listed in the following table.

Common Date Display Formats

Method Description Returns
toTimeString() Converts the military time to a string.
toLocaleTimeString() Converts the time to a string.
toDateString() Converts the date to an abbreviated string.
toLocaleDateString() Converts the date to a string.
toLocaleString() Converts the date and time to a string.

Figure 2-30. Display methods of the Date object.

As with numeric and string methods, date and time methods are illustrated throughout the tutorials in conjunctions with specific JavaScript techniques. Refer back to this page for reminders of method formats.

TOP | NEXT: Events & Event Handlers