Based on the logic for this other answer I did the function for this calculation.
The date()
faults of PHP has #.
The difference compared to the other answer is that I only use the DateTime
object here
function countSemanasMes ($ano, $mes) {
$data = new DateTime("$ano-$mes-01");
$dataFimMes = new DateTime($data->format('Y-m-t'));
$numSemanaInicio = $data->format('W');
$numSemanaFinal = $dataFimMes->format('W') + 1;
// Última semana do ano pode ser semana 1
$numeroSemanas = ($numSemanaFinal < $numSemanaInicio)
? (52 + $numSemanaFinal) - $numSemanaInicio
: $numSemanaFinal - $numSemanaInicio;
return $numeroSemanas;
}
DateTime considers the first day of the week to be Monday. If I wanted to be considered a different day, we can include a parameter for the first day of the week, as pointed out in the comments:
/**
* Calcula o número de semanas de um mês
*
* @param int $ano
* @param int $mes
* @param int $primeiroDiaSemana Intervalo 1 (Segunda-Feira) até 7 (domingo), segundo ISO-8601
* @return int
*/
function countSemanasMes ($ano, $mes, $primeiroDiaSemana = 7)
{
$primeiroDiaMes = new DateTime("$ano-$mes-01");
$ultimoDiaMes = new DateTime($primeiroDiaMes->format('Y-m-t'));
$numSemanaInicio = $primeiroDiaMes->format('W');
$numSemanaFinal = $ultimoDiaMes->format('W') + 1;
// Última semana do ano pode ser semana 1
$numeroSemanas = ($numSemanaFinal < $numSemanaInicio)
? (52 + $numSemanaFinal) - $numSemanaInicio
: $numSemanaFinal - $numSemanaInicio;
if ($primeiroDiaMes->format('N') > $primeiroDiaSemana)
$numeroSemanas--;
if ($ultimoDiaMes->format('N') < $primeiroDiaSemana)
$numeroSemanas--;
return $numeroSemanas;
}