【问题标题】:Why does iterating over weeks go wrong with PHP date?为什么 PHP 日期迭代数周会出错?
【发布时间】:2012-07-28 21:04:45
【问题描述】:

我正在编写一个 php 脚本,它在每周的星期一进行迭代。

但是脚本在 10 月 22 日之后似乎不同步了。

<?php

$october_8th = strtotime("2012-10-08");

$one_week = 7 * 24 * 60 * 60;

$october_15th = $october_8th + $one_week;
$october_22nd = $october_15th + $one_week;
$october_29th = $october_22nd + $one_week;
$november_5th = $october_29th + $one_week;

echo date("Y-m-d -> l", $october_8th) . '<br />';
echo date("Y-m-d -> l", $october_15th) . '<br />';
echo date("Y-m-d -> l", $october_22nd) . '<br />';
echo date("Y-m-d -> l", $october_29th) . '<br />';
echo date("Y-m-d -> l", $november_5th) . '<br />';

这将输出:

2012-10-08 -> Monday
2012-10-15 -> Monday
2012-10-22 -> Monday
2012-10-28 -> Sunday
2012-11-04 -> Sunday

我预计它会显示 10 月 29 日,但它卡在 28 日。

我应该如何解决这个问题?

【问题讨论】:

    标签: php date dst


    【解决方案1】:

    首选方法是使用 PHP 的与日期相关的类来获取日期。

    这些类重要地为您处理夏令时边界,其方式是手动将给定的秒数添加到 Unix 时间戳(您使用的来自 strtotime() 的数字)不能。

    以下示例获取您的开始日期并循环四次,每次都将日期添加一周。

    $start_date  = new DateTime('2012-10-08');
    $interval    = new DateInterval('P1W');
    $recurrences = 4;
    
    foreach (new DatePeriod($start_date, $interval, $recurrences) as $date) {
        echo $date->format('Y-m-d -> l') . '<br/>';
    }
    

    PHP 手册链接:

    【讨论】:

    • 谢谢,这确实是我一直在寻找的优雅解决方案。
    【解决方案2】:

    在写这个问题时,我发现夏令时在 10 月 28 日结束。

    因为初始化时的日期不包含特定时间,所以会自动分配午夜。然而,当夏季结束时,这会产生一个问题。突然间,时间不再是午夜了,而是在那之前一小时,因此比您预期的早了一天。

    一个简单的解决方法是将时间初始化为中午而不是午夜:

    $october_8th = strtotime("2012-10-08 12:00");
    

    也许有更优雅的解决方案(欢迎您留下一个),但这将用于此目的。

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 1970-01-01
      • 2015-02-13
      相关资源
      最近更新 更多