views:

514

answers:

4

In Javascript, how do I get the number of weeks in a month? I can't seem to find code for this anywhere.

I need this to be able to know how many rows I need for a given month.

To be more specific, I would like the number of weeks that have at least one day in the week (a week being defined as starting on Sunday and ending on Saturday).

So, for something like this, I would want to know it has 5 weeks:

S  M  T  W  R  F  S

         1  2  3  4

5  6  7  8  9  10 11

12 13 14 15 16 17 18

19 20 21 22 23 24 25

26 27 28 29 30 31 

Thanks for all the help.

+2  A: 

You'll have to calculate it.

You can do something like

var firstDay = new Date(2010, 0, 1).getDay(); // get the weekday january starts on
var numWeeks = 5 + (firstDay >= 5 ? 1 : 0); // if the months starts on friday, then it will end on sunday

Now we just need to genericize it.

var dayThreshold = [ 5, 1, 5, 6, 5, 6, 5, 5, 6, 5, 6, 5 ];
function GetNumWeeks(month, year)
{
    var firstDay = new Date(year, month, 1).getDay();
    var baseWeeks = (month == 1 ? 4 : 5); // only February can fit in 4 weeks
    // TODO: account for leap years
    return baseWeeks + (firstday >= dayThreshold[month] ? 1 : 0); // add an extra week if the month starts beyond the threshold day.
}

Note: When calling, remember that months are zero indexed in javascript (i.e. January == 0).

Joel Potter
+2  A: 

You could use my time.js library. Here's the weeksInMonth function:

// http://github.com/augustl/time.js/blob/623e44e7a64fdaa3c908debdefaac1618a1ccde4/time.js#L67

weeksInMonth: function(){
  var millisecondsInThisMonth = this.clone().endOfMonth().epoch() - this.clone().firstDayInCalendarMonth().epoch();
  return Math.ceil(millisecondsInThisMonth / MILLISECONDS_IN_WEEK);
},

It might be a bit obscure since the meat of the functionality is in endOfMonth and firstDayInCalendarMonth, but you should at least be able to get some idea of how it works.

August Lilleaas
How would you call the function in another script? (I'm not too good with Javascript just yet)
stjowa
Include the js file on your page, and do something like `new Time(2008, 11).weeksInMonth()`.
August Lilleaas
A: 
function weeksinMonth(m, y){
 y= y || new Date().getFullYear();
 var d= new Date(y, m, 0);
 return Math.floor((d.getDate()- 1)/7)+ 1;     
}
alert(weeksinMonth(3))

// the month range for this method is 1 (january)-12(december)

kennebec
A: 

This ought to work even when February doesn't start on Sunday.

function weekCount(year, month_number) {

    // month_number is in the range 1..12

    var firstOfMonth = new Date(year, month_number-1, 1);
    var lastOfMonth = new Date(year, month_number, 0);

    var used = firstOfMonth.getDay() + lastOfMonth.getDate();

    return Math.ceil( used / 7);
}
Ed Poor