Get Start and End Days for a Given Week in PHP

前端 未结 16 1866
囚心锁ツ
囚心锁ツ 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')
        );
    }
    }
    
    0 讨论(0)
  • 2020-12-01 04:03
    function weekRange($year, $week){
            $dateFrom = new \DateTime();
            $dateFrom->setISODate($year, $week);
            $dateTo = new \DateTime();
            $dateTo->setISODate($year, $week, 7);
    
            return array(
                'week' => $dateFrom->format('Y-W'),
                'start'=> $dateFrom->format('Y-m-d'),
                'end' => $dateTo->format('Y-m-d')
            );
        }
    

    Example:

    $weekInformation = weekRange(2020, 38);
    
    echo $weekInformation['start']; 
    // Display: 2020-09-14
    
    echo $weekInformation['end']; 
    // Display: 2020-09-20
    
    0 讨论(0)
  • 2020-12-01 04:07

    Apparently 'w' formatting value of date() or the format method of a DateTime object will return the day of the week as a number (by default, 0=Sunday, 1=Monday, etc)

    You could take this and subtract it's value as days from the current day to find the beginning of the week.

    $start_date = new DateTime("2009-05-13");
    $day_of_week = $start_date->format("w");
    
    $start_date->modify("-$day_of_week day");
    

    $start_date will now be equal to the Sunday of that week, from there you can add 7 days to get the end of the week or what-have-you.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-01 04:08

    I have decided to go with the approach at http://boonedocks.net/mike/archives/114-Figuring-the-Start-of-the-Week-with-PHP.html instead.

    0 讨论(0)
  • 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');
    
    0 讨论(0)
提交回复
热议问题