PDA

View Full Version : How many Days in a Month



Dormilich
06-05-2012, 07:06 AM
based on felgallís idea (http://www.codingforums.com/showpost.php?p=1229722&postcount=2):

function daysInAMonth(month, year)
{
return (32 - new Date(year, month-1, 32).getDate());
}

xelawho
06-05-2012, 07:20 AM
why not just


function DaysInMonth(yr,mth) {
return new Date(yr,mth,0).getDate();
}
?

Dormilich
06-05-2012, 07:26 AM
interesting, never thought to use underflow.

felgall
06-05-2012, 08:07 AM
based on felgallís idea (http://www.codingforums.com/showpost.php?p=1229722&postcount=2)

At least that post of mine got you thinking about it even if you didn't quite get to the simplest solution.

Philip M
06-05-2012, 08:30 AM
Just for the record:-


<script type = "text/javascript">

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

var d = new Date();
alert("Number of days in this month:- " + d.daysinMonth());

var Mth = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var i = 0;
var yr = 2012;
var Arr = [];
var dt = new Date(yr, 0, 1);
while(i < 12) {
Arr[i]= Mth[i]+' has '+dt.daysinMonth()+' days';
dt.setMonth(++i);
}

alert('Days in each Month of '+yr+'\n\t'+Arr.join('\n\t'))

</script>

Dormilich
06-05-2012, 09:08 AM
At least that post of mine got you thinking about it even if you didn't quite get to the simplest solution.

itís still considerably shorter than anything I had seen until then. but nevertheless, your leap year solution got me thinking how to tackle this problem in the not-so-obvious way.

@Philipp_M: I also considered extending Date, but left it to the reader (i.e. you) as it should pose no problem to rewrite it.