PHP: How many weeks in a particular month

So I’m writing a calendar app and was trying to figure out the weeks in the month for generating the display from a template.

Here’s my (assumedly clunky) response.

There’s a condensed version at the bottom that does the same thing:

function getWeeks_in_month($month, $year)
{
	#get start date
	$startDate = mktime(12,0,0, $month, 1, $year);

	# find empty days at stop of month
	$emptyDays = (date('N', $startDate) == 7) ? 0 : date('N',
	$startDate);

	# add to days of month to get 'total'
	$monthDays = date('t', $startDate);

	return ceil(($emptyDays + $monthDays)/7);
}

function getWeeks_in_month($month, $year)
{
	return ceil((((date('N', mktime(12,0,0, $month, 1, $year))
	== 7) ? 0 : date('N', mktime(12,0,0, $month, 1, $year))) +
	date('t', $startDate))/7);
}

Leave a Reply

%d bloggers like this: