为什么迭代数周的PHP日期出错了?

Mar*_*vel 2 php date dst

我正在写一个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 />';
Run Code Online (Sandbox Code Playgroud)

这将输出:

2012-10-08 -> Monday
2012-10-15 -> Monday
2012-10-22 -> Monday
2012-10-28 -> Sunday
2012-11-04 -> Sunday
Run Code Online (Sandbox Code Playgroud)

我希望它可以说是十月二十九日,但它会在28日陷入困境.

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

sal*_*the 5

首选的选择是使用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/>';
}
Run Code Online (Sandbox Code Playgroud)

PHP手册链接: