以为有人会发布这个,但找不到任何东西。试图找出最优雅的方式来确定我们在任何特定时间的17周赛季中的哪一周。我的想法是增加自2014年9月4日开始周以来的周数。接下来的星期四是新一周的开始:
Week 1 - 2014-09-4
Week 2 - 2014-09-11
Week 3 - 2014-09-18
等等......
尝试创建一个简单的函数,我可以在PHP中调用它来获取它的周数。建议?
答案 0 :(得分:1)
我不知道最短的方式,但在这种情况下我们可以使用DatePeriod
:
$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;
这应该产生:
我们在第4周
最后$dates
应该看起来像(出于可视化目的):
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
)