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

pis*_*tou 3 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');
}
Run Code Online (Sandbox Code Playgroud)

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

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

有没有办法避免这种错误?

bis*_*hop 5

您需要使用ISO年份,格式为"o":

$yearweeks[$date->format('oW')] = 'W' . $date->format('W-o');
Run Code Online (Sandbox Code Playgroud)

PHP date文档:

Ø

ISO-8601年份编号.它具有与Y相同的值,除了如果ISO周数(W)属于上一年或下一年,则使用该年代.(在PHP 5.1.0中添加)

例子:1999年或2003年