PHP 的 DateTime->modify('next week') 中缺少一周



我想我完全了解ISO 8601,一年的第一周是有星期一的一周。但是,我在PHP(5.6)日期时间类中遇到了一种奇怪的行为。

这是我的代码:

$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的启发,基于这个类似的问题,我找到了一个解决方案:

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

而不是

echo $point->format('YW')

生产:

...
200852
200901
200902
...

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

o ==> ISO-8601年号。这与 Y 具有相同的值,除了如果 ISO周数(W)属于上一年或下一年,该年是 改用。(在 PHP 5.1.0 中新增)

最新更新