Missing week in PHP DateTime-> modify ('next week')

I think I am fully aware of ISO 8601 and that the first week of the year is the week in which there is Monday. However, I met strange behavior in PHP (5.6) DateTime Class.

Here is my code:

$start = new DateTime('2009-01-01 00:00'); $end = new DateTime(); $point = $start; while($point <= $end){ echo $point->format('YW'); $point = $point->modify('next week'); } 

It does the right thing

 200901 200902 200903 ... 

But if I choose to start something earlier in 2008, for example $start = new DateTime('2008-01-01 00:00'); , then we get a different result:

 ... 200852 200801 // <=== 2008?? 200902 200903 ... 

Is this a PHP bug or am I missing something?

+5
source share
2 answers

Trained with this and finally figured it out

 $start = new DateTime('2008-12-29 00:00'); $end = new DateTime('2009-01-7 00:00'); $point = $start; while($point <= $end){ echo $point->format('YW') . "\t"; echo $point->format('md-Y') . "\n"; $point = $point->modify('next week'); } 

So, the first date is 2008-12-29 . So Y is correct. But 2008-12-29 also week 1 . So W also correct

https://3v4l.org/JZtqa

+4
source

It's not a mistake! Inspired by @Machavity and based on this this similar question , I found a solution:

 echo $point->format('oW'); 

instead

 echo $point->format('YW') 

gives:

 ... 200852 200901 200902 ... 

regardless of the start date. This is truly an RTM case, as stated in the PHP manual:

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

0
source

All Articles