I’m trying to get the days of a month using JavaScript and face a problem. I’m currently using a solution mentioned here.
Here’s my code :
function getDays(month,year){
if(month=="" || year==""|| year=="--Select--"){
document. getElementById("days"). innerHTML ="";
return;
}
var months= new Array();
alert("Month in Function"+month);// To test.
alert("Year in function"+year);
months[0]="January";
months[1]="February";
months[2]="March";
months[3]="April";
months[4]="May";
months[5]="June";
months[6]="July";
months[7]="August";
months[8]="September";
months[9]="October";
months[10]="November";
months[11]="December";
var index=months.indexOf(month);
alert("Index used"+index);
var datebase = new Date(year,index,1); //nb: month = zerobased
datebase.setDate(datebase.getDate()-1);
// Also tried database=new Date(year, index, 0).getDate();
document.getElementById("days").innerHTML =datebase.getDate();// This value is skewed.
}
I get weird values for the days of the month for example, April 2012 gives me 31 days and March 2011 gives me 28 days. Any help on what I could be messing up here would be helpful.
You’re building the date using
new Date(year,index,1), which gives e.g. the 1st of March if you pass"March". You then subtract one day to get the 28st of February. Then you say that March has 28 days. This is a wrong conclusion, obviously.You’d need to build using: