Tuesday 27 April 2010

The number of days in a month

Bombastic and verbose but fast
Date.prototype.isLeapYear = function()
{
    var y = this.getFullYear();
    return y % 4 == 0 && y % 100 != 0 || y % 400 == 0;
};

Date.prototype.getDaysInMonth = function()
{
    return arguments.callee[this.isLeapYear() ? 'L' : 'R'][this.getMonth()];
};

// durations of months for the regular year
Date.prototype.getDaysInMonth.R = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// durations of months for the leap year
Date.prototype.getDaysInMonth.L = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
Shorter and longer
Date.prototype.getDaysInMonth = function ()
{
    var here = new Date(this.getTime());
    here.setDate(32);
    return 32 - here.getDate();
};
Laconic but long almost as previous
Date.prototype.getDaysInMonth = function()
{
    return 32 - (new Date(this.getFullYear(), this.getMonth(), 32)).getDate();
};

Date.prototype.getDaysInMonth = function()
{
    return (new Date(this.getFullYear(), this.getMonth() + 1, 0)).getDate();
};

No comments:

Post a Comment