douyou1937 2014-09-30 03:56
浏览 51
已采纳

通过PHP将周数添加到周开始日期,获得当前的NFL季节

Thought someone would have posted this already, but couldn't find anything. Trying to figure out the most elegant way to figure out which week of the 17 week season we are in at any given time. My thought is to add the number of weeks since the starting week which is September 4, 2014. Every following Thursday is the start of a new week:

Week 1 - 2014-09-4
Week 2 - 2014-09-11
Week 3 - 2014-09-18

And so on...

Trying to create a simple function that I can call in PHP to get which week number it is. Suggestions?

  • 写回答

1条回答 默认 最新

  • dongyizhuang0134 2014-09-30 04:29
    关注

    I don't know the shortest way, but we could use DatePeriod for this case:

    $today = new DateTime(); // todays date
    $begin_date = '2014-09-4'; // start of nfl
    $begin = new DateTime($begin_date); // create a date time
    $i = 1; // first week number
    $end_date = clone $begin;
    $end_date->modify('+17 weeks'); // create the ending week based on the first week of nfl + 17 weeks form that date
    $interval = new DateInterval('P1W'); // interval 1 week
    $range = new DatePeriod($begin, $interval, $end_date);
    $dates = array();
    $found = false;
    foreach($range as $date) {
        if($date >= $today && !$found) { // loop each weeks, if we are inside that week, set it
            $found = true;
            $current_week = 'We are in Week ' . ($i - 1);
        }
        $dates['Week ' . $i] = $date->format('Y-m-d'); // normal week range filling
        $i++;
    }
    
    echo $current_week;
    

    This should yield:

    We are in Week 4

    And $dates in the end should look like (for visualization purposes):

    Array
    (
        [Week 1] => 2014-09-04
        [Week 2] => 2014-09-11
        [Week 3] => 2014-09-18
        [Week 4] => 2014-09-25
        [Week 5] => 2014-10-02
        [Week 6] => 2014-10-09
        [Week 7] => 2014-10-16
        [Week 8] => 2014-10-23
        [Week 9] => 2014-10-30
        [Week 10] => 2014-11-06
        [Week 11] => 2014-11-13
        [Week 12] => 2014-11-20
        [Week 13] => 2014-11-27
        [Week 14] => 2014-12-04
        [Week 15] => 2014-12-11
        [Week 16] => 2014-12-18
        [Week 17] => 2014-12-25
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?