将一天添加到日期的代码返回日期之前的日期: 2009-09-30 20:24:00日期后增加一天应滚动到下个月:1970-01-01 17:33:29

<?php

    //add day to date test for month roll over

    $stop_date = date('Y-m-d H:i:s', strtotime("2009-09-30 20:24:00"));

    echo 'date before day adding: '.$stop_date; 

    $stop_date = date('Y-m-d H:i:s', strtotime('+1 day', $stop_date));

    echo ' date after adding one day. SHOULD be rolled over to the next month: '.$stop_date;
?>

我之前用过类似的代码,这里我做错了什么?


当前回答

$date = new DateTime('2000-12-31');

$date->modify('+1 day');
echo $date->format('Y-m-d') . "\n";

其他回答

简单的阅读和理解方式:

$original_date = "2009-09-29";

$time_original = strtotime($original_date);
$time_add      = $time_original + (3600*24); //add seconds of one day

$new_date      = date("Y-m-d", $time_add);

echo $new_date;
<?php

function plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time) {
    return date($getFormat,strtotime(date($getFormat,$Old_Time).$Plus_Time));
}

$Old_Time = strtotime("now");
$Plus_Time = '+1 day';
$getFormat = 'Y-m-d H:i:s';

echo plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time);

?>

虽然我同意Doug Hays的回答,但我要在这里说一下,您的代码不工作的原因是因为strtotime()期望将INT作为第二个参数,而不是字符串(甚至是表示日期的字符串)

如果你打开最大错误报告,你会看到这是一个E_NOTICE级别的“非格式良好的数值”错误。

$date = new DateTime('2000-12-31');

$date->modify('+1 day');
echo $date->format('Y-m-d') . "\n";

modify()方法,可用于向现有DateTime值添加增量。

用当前日期和时间创建一个新的DateTime对象:

$due_dt = new DateTime();

一旦你有了DateTime对象,你可以通过添加或减去时间段来操作它的值:

$due_dt->modify('+1 day');

你可以在PHP手册上阅读更多。