Mastering JavaScript Dates: Instances of the Date Object - Doc JavaScript | WebReference

Mastering JavaScript Dates: Instances of the Date Object - Doc JavaScript


Instances of the Date Object

JavaScript stores all dates as the number of milliseconds since January 1, 1970 00:00:00. Therefore, trying to handle preceding dates results in an error, or even crashes the browser.

JavaScript does not have a date data type. However, the Date object and its methods enable you to work with dates in your scripts. In order to take advantage of the Date object's features, you must first create an instance reflecting a specific date:

var varName = new Date([arguments]);

varName is a variable name or a property of an existing object. arguments can be one of the following:

There are several other possible arguments, but these are the most important ones. The Macintosh version of Netscape Navigator 2.0x is one day in the future. In order to fix this bug in your script, use the following function:

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

Since some of the methods in this function are beyond the scope of our column, we'll just show you how to use it. Once you've created an instance of the Date object, simply hand it to the function in the following fashion:

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);

http://www.internet.com


Created: September 11, 1997
Revised: April 7, 1998

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