Quote:
Originally Posted by felgall
I would suspect that the code will report the wrong answer for the year 4882 and 8182 which are the only 2 four digit leap years not divisible by 4.
Leap year rules.
1. Divisible by 4 and not divisible by 100.
2. Divisible by 400.
3. Year less 1582 divisible by 3300.
While most code now implements the first two leap year rules most people don't even know about the third one in order to implement it. Not that it is likely that anyone is likely to need to worry about it for a couple of thousand years or so - and so that the code doesn't give correct results for those years is unlikely to matter for most applications.
Similar code could be implemented on the Date object to report if the date stored in it is a leap year. That way you could determine if a date is in a leap year without having to extract the year to test it.
Code:
Date.prototype.isLeapYear = function(){
return (new Date(this.getFullYear(),1,29).getMonth()===1);
}
|
I will generally avoid "Fixing" the year and allow the user to pass or use the year to be tested, more friendly and flexible.
I tested the function against published tables, the function works fine, you have to remember that the reference is the tables within javascript. Any limitations are down to the scope of the table of rules which will be far more accurate than using modulo math to derive the answer.
So for the now an present, nothing wrong with the method as I really don't see javascript existing in about 2,000 years or more either.
So in fairness, we are plain sailing for a bout 3,000 years until the hic-up occurs but by then I am sure that any javascript that may still exist will have had the date object "Fixed" by then.
The main problem with any method is that it does have a limitation that means is simply that the length of the vernal equinox year will have changed by an amount that cannot be accurately predicted past a certain point and that is where you pick up on this limitation.
So for the sake of argument, the functions good for a few thousand years and at the whim of Microsoft ensuring that the date / time rules tables are maintained in the operating system.