Based on logic of this other answer made function for that calculation.
The functions date()
of PHP has a problem with the year 2038.
The difference if compared to the other answer is that here I use exclusively the object of DateTime
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 you wanted it 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;
}
You want to know the number of the week in relation to the year, or the sum of weeks in a month?
– gmsantos
number of weeks in a month
– Alexandre Sousa
Do you need the week to start on what day? Sunday or Monday?
– gmsantos
Have any answers solved your problem? If yes, don’t forget to mark this answer as correct.
– gmsantos