Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I think I am fully aware of ISO 8601 and that the first week of a year is the week that has a Monday in it. However I came across a 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');
}

This puts out correctly

200901
200902
200903
...

But if I pick as a start date something earlier in 2008 like $start = new DateTime('2008-01-01 00:00'); then I get a different result:

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

Is this a PHP bug or am I'm missing something here?

like image 538
Steven M Avatar asked Jul 07 '16 12:07

Steven M


1 Answers

Tinkered 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('m-d-Y')  . "\n";
   $point = $point->modify('next week');
}

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

https://3v4l.org/JZtqa

like image 108
Machavity Avatar answered Sep 28 '22 04:09

Machavity