Sunday, July 01, 2007

Some reader contributions to Calendar tutorial

When I started SZOJ I promised myself I wouldn't abruptly shut down the blog if I lost interest; I'd just go radio silent until my interest was piqued again. That said, it's been a long while. So here are two things:

Rory Parle wrote in to point out you can use Math.ceil to determine the number of rows you'd need to safely render a calendar:

Math.ceil((monthLength + startingDay) / 7);

Michiel van der Blonk suggested a way to determine the number of days in a month:

var d = new Date(nYear, nMonth + 1, 0); // nMonth is 0 thru 11

The mechanism here is the Date constructor will attempt to convert year, month and day values to the nearest valid date. So in the above code, nMonth is incremented to find the following month, and then a Date object is created with zero days. Since this is an invalid date, the Date object defaults to the last valid day of the previous month — which is the month we're interested in to begin with. Then getDate() returns the day (1-31) of that date — voilá, we have the number of days.

Bonus: it also seems to automatically correct for leap year. It feels like a hack but it seems to work consistently.

Thanks to Rory and Michiel for their contributions.