Get Start and End Days for a Given Week in PHP

I would take advantange of PHP’s strtotime awesomeness:

function x_week_range(&$start_date, &$end_date, $date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    $start_date = date('Y-m-d', $start);
    $end_date = date('Y-m-d', strtotime('next saturday', $start));
}

Tested on the data you provided and it works. I don’t particularly like the whole reference thing you have going on, though. If this was my function, I’d have it be like this:

function x_week_range($date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    return array(date('Y-m-d', $start),
                 date('Y-m-d', strtotime('next saturday', $start)));
}

And call it like this:

list($start_date, $end_date) = x_week_range('2009-05-10');

I’m not a big fan of doing math for things like this. Dates are tricky and I prefer to have PHP figure it out.

Leave a Comment