Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through Calendar Weeks

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?

like image 520
Tina Turner Avatar asked Feb 17 '26 20:02

Tina Turner


1 Answers

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
like image 60
moorscode Avatar answered Feb 20 '26 09:02

moorscode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!