Get Start and End Days for a Given Week in PHP

前端 未结 16 1888
囚心锁ツ
囚心锁ツ 2020-12-01 03:49

I\'m trying to get the week range using Sunday as the start date, and a reference date, say $date, but I just can\'t seem to figure it out.

For example,

16条回答
  •  日久生厌
    2020-12-01 04:08

    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.

提交回复
热议问题