PHP 的 DateTime->modify('next week') 中缺少星期

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

我想我完全了解 ISO 8601,并且一年的第一周是其中有星期一的那一周。但是我在 PHP (5.6) DateTime Class.

中遇到了一个奇怪的行为

这是我的代码:

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

这输出正确

200901
200902
200903
...

但是如果我选择 2008 年早些时候的日期作为开始日期,例如 $start = new DateTime('2008-01-01 00:00');,那么我会得到不同的结果:

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

这是 PHP 错误还是我遗漏了什么?

修改了这个,终于弄明白了

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

所以这里的第一个约会是2008-12-29。因此 Y 是正确的。但是 2008-12-29 也是 第 1 周 。所以W也是正确的

https://3v4l.org/JZtqa

这不是错误!受@Machavity 的启发并基于此 this similar question 我找到了一个解决方案:

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

而不是

echo $point->format('YW')

产生:

...
200852
200901
200902
...

无论什么时候开始。正如 PHP 手册所述,这确实是一个 RTM 案例:

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