JavaScript Date Object Extensions: Guide
Besides being useful (hope so) this script shows a technique that is unique to dynamic languages like JavaScript: extension of built in objects, which means that including the script in a html document adds methods and properties to every instance of the intrinsic Date object.
The main benefits of this script are:
- Determine leap years: The method
isLeapYear()and the functionDate.leapYear()determine if a given year is a leap year. - Compare dates: The method
compareTo()and the functionDate.compare()return the difference of two dates in milliseconds. - Add/subtract dates: The method
add()and the functionDate.addDate()perform simple date arithmetics.
Note that the y2k issues with getYear() etc. aren't much of a problem anymore, since nobody is still using the buggy old browsers. So the getFullYear() implementation and the following paragraphs are obsolete, I just left them in because of nostalgia
.
JavaScript 1.2 and below (implemented in Netscape Navigator 4.05 and below) and JScript Version 1 (implemented in Microsoft Internet Explorer 3) provide the problematic Date object methods getYear() and setYear().
they a) yield a y2k problem and b) behave differently in various browsers and even in different versions of the same browser. See Danny Goodman's articles about JavaScript dates for more details.
JavaScript 1.3 (Netscape Navigator 4.06 and up) and JScript 3 (Microsoft Internet Explorer 4 and up) introduced the ECMA script methods getFullYear() and setFullYear(). This script simulates their implementation. (I use the term simulate because this implementation is based on the built in getYear() and setYear() implementations and therefore suffers from some flaws compared to the built in getFullYear() and setFullYear()). More details in the API Reference.
Back to Date Extensions