Awesome Leap Year Calculation in JavaScript



What is a Leap Year (Wikipedia Definition)

leap year (or intercalary or bissextile year) is a year containing one additional day (or, in the case of lunisolar calendars, a month) in order to keep the calendar year synchronized with the astronomical or seasonal year. Because seasons and astronomical events do not repeat in a whole number of days, a calendar that had the same number of days in each year would, over time, drift with respect to the event it was supposed to track. By occasionally inserting (or intercalating) an additional day or month into the year, the drift can be corrected. A year that is not a leap year is called a common year. [1]

Leap Year Algorithm

Below a simple algorithm for determining a leap year is introduced.

if year is divisible by 400 then
   is_leap_year
else if year is divisible by 100 then
   not_leap_year
else if year is divisible by 4 then
   is_leap_year
else
   not_leap_year

How to Determine a Leap Year in JavaScript - Attempt #1

// monkey-patching / extend the Date object and add
isLeapYear

The following solutions uses the algorithm shown above to determine if a given year is a leap year.

Date.prototype.isLeapYear = function(utc) {
    var y = utc ? this.getUTCFullYear() : this.getFullYear();
    return !(y % 4) && (y % 100) || !(y % 400);
};
// or

function isLeapYear (utc) {
    var y = utc ? this.getUTCFullYear() : this.getFullYear();
    return !(y % 4) && (y % 100) || !(y % 400);
};

How to Determine a Leap Year in JavaScript - Attempt #2

The following solutions uses the JavaScript Date object. The Date object contains internal checking mechanism for leap year as defined by the ECMAScript Specification section 15.9.1.3 Year Number

Date.prototype.isLeapYear = function(year) {
    return new Date(year, 1, 29).getMonth() == 1;
};

// or

function isLeapYear (year) {
    return new Date(year, 1, 29).getMonth() == 1;
}

It's safer, simpler and faster to use the date object to determine the leap year. 
NB: Providing the base Date object for every language is implemented properly, this implementation can easily be ported

References
1. WikiPedia Leap Year 

Comments

Popular posts from this blog

JavaScript Module Pattern: 2 Forms

Pseudo-Random UUID Generation with mask support

Mocking Ajax with the JQuery Mockjax Library