使用1个月递增日期时出错

时间:2014-02-06 13:11:30

标签: php datetime

我面临一个奇怪的问题,即以下案例增加一个月的日期 对于日期输入为2014-01-31我得到2014-03-03,而它应该是“2014-02-28”

我正在使用以下代码

$time = strtotime("2014-01-31");
$final = date("Y-m-d", strtotime("+1 month", $time));

1 个答案:

答案 0 :(得分:3)

在1月30日或31日使用时,php中的+1个月有意外行为。你将在三月份得到一个约会。这是因为php online将月份数提高了1(因此2014-01-31将成为2014-02-31。这不存在因此php会将此更正为2012-02-28 + 3.

这将在月底为您提供正确的结果。

$d = new DateTime( '2014-01-31' );
$d->modify( 'last day of +1 month' );
$final = $d->format( 'Y-m-d' );

这可以在php手册中解释:http://php.net/manual/en/function.strtotime.php#107331