Pergunta

Lets say I have $year and $week variables that contain the ISO 8601 representation of a week. I want to calculate the previous and the next weeks. This is an easy task in most parts of the year because I just have to increment or decrement the $week variable, but in the border of two years I need to check if we started a new year.

I created something like this:

public function nextweek($year, $week)
{
   $maxweek = 0;//@TODO
   if ($week + 1 == $maxweek)
   {
      $year++;
      $week = 1;
   }
   else
   {
      $week++;
   }
   $nextweek = $year.'/'.$week;
   return $nextweek;
}

Is there a completion, better solution or a built in function for this?

Foi útil?

Solução

Finally I found a solution.

public function nextweek($year, $week)
{
   $date = new DateTime;
   $date->setISODate($year, ++$week);
   if (!($date->format('W') == $week))
   {
      $week = '01';
      ++$year;
   }
   return $year.'/'.$week;
}

Outras dicas

Or for PHP < 5.2

function nextweek($year, $week) {
    $nextWeek = strtotime($year.'W'.sprintf("%02d", $week)) + (7 * 24 * 60 * 60);
    return date('Y/W', $nextWeek);
}

There is a problem with year wrap..for nextweek(2013, 52) it prints 2013/01. Haven't found the error yet..so better stick with DateTime.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top