为什么用PHP date进行数周的迭代会出错? - php

我正在写一个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的与日期相关的类来获取日期。

这些类很重要地为您处理了日光节约的边界,这种方式无法将给定的秒数手动添加到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手册链接:

The DatePeriod class
The DateInterval class
The DateTime class

PHP strtotime困境 - php

有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00�…

PHP-全局变量的性能和内存问题 - php

假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…

php-casperjs获取内部文本 - php

我正在为casperjs使用php包装器-https://github.com/alwex/php-casperjs我正在网上自动化一些重复的工作,我需要访问一个项目的innerText,但是我尚不清楚如何从casperjs浏览器访问dom。我认为在js中我会var arr = document.querySelector('label.input…

php:拆分字符串,直到第一次出现数字 - php

我有像cream 100G sup 5mg Children 我想在第一次出现数字之前将其拆分。所以结果应该是array( array('cream','100G'), array('sup','5mg Children') ); 可以告诉我如何为此创建图案吗?我试过了list(…

将大字符串分成多个小字符串-PHP - php

我从数据库中获取了一个长字符串,我需要对其进行解析,以使其不包含一个大字符串,而是多个,其中每个字符串都有2个字符。让我们以示例为例:我连接到表,获取此字符串:B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5,之后,我必须对字符串进行解析,因此:B1 C1 F4 G6 H4 I7 J1 J8 L5 O6 P2 Q1 R6 T5 U8 V1…