我遇到了一个奇怪的问题,对于以下情况,日期增加一个月
对于日期输入为 2014-01-31
我得到2014-03-03
而它应该是“2014-02-28”
我正在使用以下代码
$time = strtotime("2014-01-31");
$final = date("Y-m-d", strtotime("+1 month", $time));
最佳答案
当您在 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
关于php - 将日期增加 1 个月时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21603980/