【问题标题】:Missing Week in PHP's DateTime->modify('next week')PHP 的 DateTime->modify('next week') 中缺少一周
【发布时间】:2016-07-07 12:32:45
【问题描述】:

我认为我完全了解 ISO 8601,并且一年的第一周是其中有星期一的那一周。但是我在 PHP (5.6) DateTime 类中遇到了一个奇怪的行为。

这是我的代码:

$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 错误还是我在这里遗漏了什么?

【问题讨论】:

  • 因为它是 2009 年的第一周,请尝试echo $point-&gt;format('YW') ." --&gt; ". $point-&gt;format('Y-m-d'); 希望你会明白这件事

标签: php datetime week-number


【解决方案1】:

解决了这个问题,终于弄明白了

$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

【讨论】:

  • 那么这是一个 PHP 错误。如果您逐年迭代,您会期望它正确计算第 53 周,对吗?
  • @StevenM 这不是错误。这实际上就是 ISO8601 的看法。 Check out this Wikipedia article 你会注意到 Mon 29 Dec 20082009-W01-1
  • 是的,完全正确 - 但 PHP 在 2008 的第一周而不是 2009....
  • @StevenM No. 12-29-2008 仍在 2008 年。这就是 Y 所做的。如果您改用o(ISO8601 年),您会看到它是在 2009 年。错误在您的脚本中,而不是 PHP 3v4l.org/nEMmj
【解决方案2】:

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

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

而不是

echo $point->format('YW')

产生:

...
200852
200901
200902
...

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

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

【讨论】:

    猜你喜欢
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2022-01-07
    • 1970-01-01
    相关资源
    最近更新 更多