Number of weeks in a month

Asked

Viewed 7,129 times

16

I would like to know how to calculate the number of weeks you have a month

 D  S  T  Q  Q  S  S
                   1    => Semana 1
 2  3  4  5  6  7  8    => Semana 2
 9 10 11 12 13 14 15    => Semana 3
16 17 18 19 20 21 22    => Semana 4
23 24 25 26 27 28 29    => Semana 5
30 31                   => Semana 6
  • You want to know the number of the week in relation to the year, or the sum of weeks in a month?

  • number of weeks in a month

  • 1

    Do you need the week to start on what day? Sunday or Monday?

  • Have any answers solved your problem? If yes, don’t forget to mark this answer as correct.

5 answers

9

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;
}
  • 3

    Much better than my implementation. + 1.

  • Just like the @Newtonvagner solution, it also failed for 02/2015.

  • @Rodrigorigotti Datetime considers the first day of the week as Monday, so February has 5 weeks.

  • 3

    @gmsantos I believe that the first day of the week should be parameterizable, after all depending on the case the week starts on Monday or Sunday.

  • @Rodrigorigotti, let’s ask the author for more details. I haven’t found a simple way to parameterize the day of the beginning of the week with Datetime.

  • @gmsantos 'Correction' possible: 1 - Get the first day of the week via date('N',*) or equivalent in Datetime. 2 - Calculate offset, in days, against Sunday = 1. 3 - Add offset to $data and $dataFimMes dates.

  • @gmsantos his code almost helped me too but wanted to know how to do for the week I want him to calculate, example: Wednesday

  • 1

    @Lucasantonio did not understand your doubt. How about creating a new question explaining in more detail with a minimum example?

  • @gmsantos I need something that returns according I spend the week example: Tuesday - fair and return me how many Tuesdays have in the month, but I need you to accept 1 more months.

  • 1

    would be a different implementation than @Lucasantonio. create a new question.

Show 5 more comments

7

According to your documentation, the function Date() allows the parameter W, which returns the week number of a given day.

Then, to calculate the number of weeks, subtract the Week Number the last day of the month Week Number of the first.

I’m not a PHP programmer, but I created a snippet that should make the calculation right for you.

<?php

$date = new DateTime();
$query_date = '2010-02-04';

$source_date = strtotime($query_date);

$dat_ini = new DateTime(date('Y-m-01', $source_date));
$dat_fin = new DateTime(date('Y-m-t', $source_date));

$NumeroSemanas = (int)$dat_fin->format('W') - (int)$dat_ini->format('W') + 1;
?>

2

This is a problem that has several ways to implement a solution. My idea would be to take the amount of days a month has, split by seven (the amount of days in a week) and take the entire amount of that result.

Translating into code:

<?php
function getNumSemanas($mes, $ano, $diaInicialSemana = 'Sunday', $calendario = CAL_GREGORIAN) {
    $diasEmUmMes = cal_days_in_month($calendario, $mes, $ano);
    $numSemanas = 1;
    for ($i=1; $i<=$diasEmUmMes; $i++) {
        if (date('l', strtotime("$i-$mes-$ano")) === $diaInicialSemana && !($i === 1 && date('l', strtotime("$i-$mes-$ano")) === $diaInicialSemana)) {
            $numSemanas++;
        }
    }

    return $numSemanas;
}
  • Sorry, I’ve seen that this solution does not work. I’m seeing another solution :)

  • Ready, corrected! ;)

  • 2

    Does not work with dates from 2038

2

The function below finds the number of weeks in a given month, assuming Monday as the first day of the week.

function weeks_in_month($month, $year) {
// Start of month
$start = mktime(0, 0, 0, $month, 1, $year);

// End of month
$end = mktime(0, 0, 0, $month, date('t', $start), $year);

// Start week
$start_week = date('W', $start);

// End week
$end_week = date('W', $end);

if ($end_week < $start_week) { // Month wraps
  return ((52 + $end_week) - $start_week) + 1;
}

return ($end_week - $start_week) + 1;
}


echo '08/2014 tem: ' . weeks_in_month('08', '2014') . ' semanas';

// retorno
// 08/2014 tem: 5 semanas 

source

  • Does not work with dates from 2038

-2

Follows a possible solution:

/**
 * Calcula a quantidade de Semanas em um mes
 * 
 * @param string $mesAno Mes e Ano no formato MM/AAAA. Ex.: 05/2014
 * @return int Quantidade de semanas no mes
 */
function quantidadeSemanasMes($mesAno)
{
    $data = '01/'.$mesAno;
    $start = \DateTime::createFromFormat('d/m/Y', $data);

    $end = clone $start;
    $end->add(new \DateInterval("P1M"));
    $end->sub(new \DateInterval("P1D"));

    return ceil(($start->format('w') + $end->format('d')) / 7);
}

echo quantidadeSemanasMes('02/2012'); // retorna 5
  • Failure for 02/2015 (has 4 weeks).

  • Corrected. Thank you.

  • 1

    Now it’s wrong for all the other months :)

  • You can give an example, I tested it here and it’s working.

  • @Newtonwagner my fault, I thought your change fixed the problem of the week start on Monday.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.