php 日期加法跳过天数

php date addition skipping days

我有一个日期,需要加上 24 个月 (而不是 2 年)。这是我试过的:

strtotime("+24 months", $mydate);

如果我的日期是 20th Dec 2013,那么计算出的日期是 10th Dec 2015,而我的预期日期是 20th Dec 2015

我知道,幕后发生了什么:

2 Year: 365 days x 2 = 730 days
24 Months: 24 x 30days = 720 days

这给了我缺少的 10 天。但是这个问题怎么解决呢。

Java 中我们有 Calendar class,它负责此类计算。但是,我在这里找不到任何东西。

这个问题能解决吗?或者我需要手动处理?

DateTime 在这里应该可以完美运行:

$date = new DateTime("20th Dec 2013");
echo $date->format("d-m-Y");
$date->add(new DateInterval('P24M'));
echo $date->format("d-m-Y");

输出:

20-12-2013
20-12-2015

Demo

旁注:

我无法重现您的错误:

echo date("d-m-Y", strtotime("+24 months", $mydate = strtotime("2013-12-20")));

见: http://3v4l.org/HURAt

您应该始终使用 DateTime() class 来处理类似的事情。

$date = new DateTime("UTC");

//get date in 24months time:
$date->add(new DateInterval("P24M"));

//output date:
echo $date->format("d/m/Y H:i:s");

通过使用 DateTime 和 DateInterval classes,您可以确定它会考虑闰年和日期中的其他此类不规则情况。

查看更多信息:http://php.net/manual/en/class.datetime.php

希望对您有所帮助。

$mydate = "2014-10-01";
echo date('d-m-Y',strtotime("+24 months", strtotime($mydate)));