php strtotime如何处理最后一个星期天

时间:2014-06-16 14:59:36

标签: php strtotime

当我在最后一个星期天之后尝试获取X天的时间戳时,我得到一个奇怪的结果。

echo date("Y-m-d\n", strtotime("2014-05-11 last sunday +5 days")); => 2014-05-09
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday +6 days")); => 2014-05-10
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday +7 days")); => 2014-05-18
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday +8 days")); => 2014-05-19

为什么跳过一周?它以什么顺序读取参数?

在php:5.5.4,5.5.9和5.5.10中测试。

仅当startdate是星期日时才会出现问题。

3 个答案:

答案 0 :(得分:1)

自2014-05-11实际上是一个星期日,上周日跳了一个星期,因为你想要指定日期之前的星期日当你说"上周日"。您可能需要检查您使用的绝对日期是否为星期日;并采取相应的行动。

strtotime在这里行为不可预测,因为你将不同的陈述混合成一个,所以我建议的内容

echo date("Y-m-d\n", strtotime("2014-05-11 last sunday")+5*86400);
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday")+6*86400);
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday")+7*86400);
echo date("Y-m-d\n", strtotime("2014-05-11 last sunday")+8*86400);

您可以将基准日期作为第二个参数提供给strtotime,以使事情更加清晰:

echo date("Y-m-d\n", strtotime("last sunday", strtotime('2014-05-11'))+5*86400);
echo date("Y-m-d\n", strtotime("last sunday", strtotime('2014-05-11'))+6*86400);
echo date("Y-m-d\n", strtotime("last sunday", strtotime('2014-05-11'))+7*86400);
echo date("Y-m-d\n", strtotime("last sunday", strtotime('2014-05-11'))+8*86400);

答案 1 :(得分:1)

根据PHP.NET strtotime更改日志:

  

在PHP 5.3.0之前,提供给strtotime()的时间参数的相对时间格式(例如本周,前一周,上周和下周)被解释为相对于当前日期的7天期间/时间,而不是周一至周日的一周时间。

http://sandbox.onlinephpfunctions.com/code/4bc6054b173ac81b3fd6ddf535f4fe4bfc06e98f

测试php版本> 5.3和< 5.3,你可以看到差异。

答案 2 :(得分:1)

@ puggan-se这样的复杂性!令我感到困惑的是PHP,让我KISS用于PHP。

$sample_date = strtotime('2014-05-11');
$last_sunday = strtotime('last sunday', $sample_date);
echo date("Y-m-d\n", strtotime("+5 days", $last_sunday)); // => 2014-05-09
echo date("Y-m-d\n", strtotime("+6 days", $last_sunday)); // => 2014-05-10
echo date("Y-m-d\n", strtotime("+7 days", $last_sunday)); // => 2014-05-11
echo date("Y-m-d\n", strtotime("+8 days", $last_sunday)); // => 2014-05-12