Mastering JavaScript Dates: Date Methods - Doc JavaScript | WebReference

Mastering JavaScript Dates: Date Methods - Doc JavaScript


Date Methods

In order to use an instance of the Date object in a script, you must be able to extract the day, date, month, and year attributes. You can retrieve these values by invoking a set of JavaScript methods. First, let's take a look at the following definition:

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}
var current = new Date(); // a new instance
fixDate(current);

As you already know, this code segment creates a new instance of the Date object and fixes a possible bug.

We'll use the getDate() method to extract the current day of the month (an integer from 1 to 31). For example, the following statement prints the current day of the month:

document.write(current.getDate());

The getMonth() method returns an integer from 0 to 11. 0 corresponds to January, 1 to February, and so forth. The following statement prints the index of the current month, as a number between 1 and 12 (rather than the natural 0-11 scale):

document.write(current.getMonth() + 1);

Invoke JavaScript's getYear() method to retrieve a date's year. This method returns a number equal to the current year less 1900; that is, the last two digits of the year. On Internet Explorer, however, for years greater than 1999, the getYear() method returns the full four-digit year. Therefor, you'll be much better off using getFullYear() instead of getYear(). The following code segment prints the current four-digit year:

document.write((current.getFullYear());

JavaScript also provides a method that returns the current day of the week -- getDay(). It returns an integer corresponding to the day of the week. That is, 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on. Therefore, the following statement prints the current day of the week on a 1-7 scale:

document.write(current.getDay() + 1);

Created: September 11, 1997
Revised: April 12, 2000

URL: http://www.webreference.com/js/column2/properties.html