跨年DatePeriod宽度DateInterval P7D失去新的一周

时间:2014-09-16 14:07:26

标签: php date

我正在尝试使用PHP DatePeriod进行一系列的周年纪念,如下所示:

$from = new DateTime('2014-09-16');
$to = new DateTime('2015-02-25');

$interval = new DateInterval('P7D'); // 7Days => 1 Week
$daterange = new DatePeriod($from, $interval, $to);

$yearweeks = array();
foreach($daterange as $date) {
    $yearweeks[$date->format('YW')] = 'W' . $date->format('W-Y');
}

结果很奇怪! 新年的第一周不见了。我有上一年的第一周而不是这样:

Array
(
    ...
    [201451] => W51-2014
    [201452] => W52-2014
    [201401] => W01-2014 // WTF ? /!\ [201501] => W01-2015 expected ! /!\
    [201502] => W02-2015
    [201503] => W03-2015
    ...
)

有没有诀窍可以避免这种错误?

1 个答案:

答案 0 :(得分:5)

您需要使用ISO年份,即格式' o':

$yearweeks[$date->format('oW')] = 'W' . $date->format('W-o');

来自PHP date docs

  

o

     

ISO-8601年号。除了if之外,它具有与Y相同的值   ISO周数(W)属于上一年或明年   相反使用年份。 (在PHP 5.1.0中添加)

     

例子:1999年或2003年