Web Development Tutorials




  
  

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.
  TheDate.getDate()
getDay() Returns the numeric day of the week (Sunday = 0).
  TheDate.getDay()
getMonth() Returns the numeric month of the year (January = 0).
  TheDate.getMonth()
getYear()
getFullYear()
Returns the current year.
  TheDate.getYear()
  TheDate.getFullYear()


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

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.
  TheDate.toTimeString()
toLocaleTimeString() Converts the time to a string.
  TheDate.toLocaleTimeString()
toDateString() Converts the date to an abbreviated string.
  TheDate.toDateString()
toLocaleDateString() Converts the date to a string.
  TheDate.toLocaleDateString()
toLocaleString() Converts the date and time to a string.
  TheDate.toLocaleString()

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