3

I built this function in my class:

class CalenderWeekHelper {
    public static function getCalenderWeek($year = 2016)
    {
        for ($i=1; $i <= 52; $i++)
        {
             $from = date("d.m.Y", strtotime("{$year}-W{$i}-1")); //Returns the date of monday in week
             $to   = date("d.m.Y", strtotime("{$year}-W{$i}-7")); //Returns the date of sunday in week
             $weekArray[$i] = array('start' => $from, 'end' => $to);

        }
        return $weekArray;
    }
}

And call it like this:

$kw = CalenderWeekHelper::getCalenderWeek(2015);
echo $kw[1]['start']

But it still echos me following:

01.01.1970

I just want to loop trough all calender weeks, anyone know how to solve this?

Ben
  • 8,894
  • 7
  • 44
  • 80
Tina Turner
  • 93
  • 1
  • 2
  • 4

1 Answers1

3

See the following answer for the correct format of strtotime: How to convert week number and year into unix timestamp?

The day returned is a monday, so you can add 6 days to get the sunday:

$week = sprintf('%02s', $i); // make sure it is formatted in double figures
$from = date("d.m.Y", strtotime("{$year}W{$week}")); //Returns the date of monday in week
$to   = date("d.m.Y", strtotime("{$year}W{$week} +6 days")); //Returns the date of sunday in week
Community
  • 1
  • 1
moorscode
  • 801
  • 6
  • 13
  • Thanks It works so far one question what does your first line do excatly ($week = sprintf('%02s', $i);)? – Tina Turner Oct 30 '15 at 16:25
  • You should look up http://php.net/sprintf for specific details of the function. But this way it takes the weeknumber and adds a 0 if it's below 10, so it always has a length of 2 "04". % means variable, 02 means at least 2 length and fill with 0's, 's' means output a string. – moorscode Oct 30 '15 at 17:16