...

View Full Version : Get Days in a month



Cremator
01-29-2012, 01:00 AM
Snippet to get the number of days,

Date.prototype.daysInMonth=function(mth,yr){
yr = yr || this.getFullYear();
mth = mth || this.getMonth();
return 32 - new Date(yr, mth, 32).getDate();
}
alert( new Date().daysInMonth() );

pass month & year to get the days in a month for that year.
pass month to get the number of days in the month in the current year
pass no parameters to get the number of days in the current month in the current year.

or


Date.prototype.daysInMonthPartRFC=function(partRfc){
partRfc = (partRfc)? partRfc+"/"+32 : [this.getFullYear(),this.getMonth(),32].join("/");
return 32 - new Date(partRfc).getDate();
}
alert( new Date().daysInMonthPartRFC("2012/0") );

pass a part date string made up of the year and javascript month separated by a slash or pass no argument to get days in current month in current year.

months being passed will be JavaScript months, 0 to 11.

felgall
01-29-2012, 03:16 AM
The easiest way to get the number of days in a month using JavaScript is to set the date to the zeroth day of the following month then return the day. No need to mess around with 32 or subtraction.


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

Cremator
01-29-2012, 09:12 AM
Yep I know, I have that prototype too.


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

alert( new Date().daysInThisMonthOfThisYear() );


:D

Added:
Also modded this...

Date.prototype.daysInThisMonthOfThisYearPartRFC=function(partRfc){
partRfc = (partRfc)? partRfc+"/0" : [this.getFullYear(),this.getMonth()+1,0].join("/");
return new Date(partRfc).getDate();
}
alert( new Date().daysInThisMonthOfThisYearPartRFC("2012/1") );

siberia-man
01-31-2012, 03:50 PM
Some time ago I extended for myself the Date object with the same methods. Those are:



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

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

Date.prototype.getDaysInYear = function()
{
return this.isLeapYear() ? 366 : 365;
};

Date.prototype.getFirstDay = function()
{
return (new Date(this.getFullYear(), this.getMonth(), 1)).getDay();
};

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


There are another methods (http://code.google.com/p/jsxt/source/browse/trunk/js/Date.js) that I can public here if it will be interesting.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum