1

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?

Jeff Solomon
  • 459
  • 6
  • 21

1 Answers1

2

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
)
Kevin
  • 41,694
  • 12
  • 53
  • 70