Get Start and End Days for a Given Week in PHP

前端 未结 16 1865
囚心锁ツ
囚心锁ツ 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:09

    To everyone still using mktime(), strtotime() and other PHP functions... give the PHP5 DateTime Class a try. I was hesitant at first, but it's really easy to use. Don't forget about using clone() to copy your objects.

    Edit: This code was recently edited to handle the case where the current day is Sunday. In that case, we have to get the past Saturday and then add one day to get Sunday.

    $dt_min = new DateTime("last saturday"); // Edit
    $dt_min->modify('+1 day'); // Edit
    $dt_max = clone($dt_min);
    $dt_max->modify('+6 days');
    

    Then format as you need it.

    echo 'This Week ('.$dt_min->format('m/d/Y').'-'.$dt_max->format('m/d/Y').')';
    

    Make sure to set your timezone early in your code.

    date_default_timezone_set('America/New_York');
    

提交回复
热议问题