Get Start and End Days for a Given Week in PHP

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

    Based on David Bélanger's version (unfortunatelly, my rep. won't allow me to post comment as reaction to his post..).

    When input date is monday and first day of week is set as monday, original version returns previous week, not current. Here's the little fix (with the rest of orig. function):

    if(function_exists('grk_Week_Range') === FALSE){
    function grk_Week_Range($DateString, $FirstDay=6){
    
        if(empty($DateString) === TRUE){
            $DateString = date('Y-m-d');
        }
    
        # fix
        $dayOfWeek = date('N', strtotime($DateString));
        if ($dayOfWeek == ($FirstDay +1)) { $whichWeek = 'this '; }
        else { $whichWeek = 'last '; }
    
        $Days = array(
            0 => 'monday',
            1 => 'tuesday',
            2 => 'wednesday',
            3 => 'thursday',
            4 => 'friday',
            5 => 'saturday',
            6 => 'sunday'
        );
    
        # fix   
        $DT_Min = new DateTime( $whichWeek.(isset($Days[$FirstDay]) === TRUE ? $Days[$FirstDay] : $Days[6]).' '.$DateString);
        $DT_Max = clone($DT_Min);
    
        return array(
            $DT_Min->format('Y-m-d'),
            $DT_Max->modify('+6 days')->format('Y-m-d')
        );
    }
    }
    

提交回复
热议问题