1

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.

2 Answers 2

2

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:

new Date(year, index + 1, 1);
// so, build e.g. 1 April when "March" is passed, then
// subtract one to get last day of March
Sign up to request clarification or add additional context in comments.

Comments

1

A few months ago I have to do the same thing - get the number of days that a month have in a given year. There are a lot of solutions, but the this one I think is the shortest and nicest one.

 function DaysInMonth(Month,Year){
     return (32-new Date(Year,Month,32).getDate());     
 }

The function has two parameters:

  1. Month - this is a integer value from 0 to 11, where 0 indicates January and 11 - December
  2. Year - the year

Try it:

  DaysInMonth(1,2012)
  DaysInMonth(2,2012)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.