Cross-Year DatePeriod DateInterval width P7D plays the week of the new year

I am trying to create an array of summer days using PHP DatePeriod like this:

$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');
}

      

The result is rather strange! The first week of the new year is missing. I have the first week of the previous year, and like this:

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

      

Is there a trick to avoid this mistake?

+3


source to share


1 answer


You need to use ISO year, format 'o':

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

      



From PHP date

docs
:

o

ISO-8601 number. This has the same meaning as Y, except that if the ISO week number (W) refers to the previous or next year, that year is used instead. (added in PHP 5.1.0)

Examples: 1999 or 2003

+5


source







All Articles