将一天添加到日期的代码返回日期之前的日期: 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;
?>

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


当前回答

既然您已经对代码中的错误有了答案,那么我可以从另一个角度介绍如何处理日期时间,并具体地解决您的问题。

通常你会发现自己在解决问题的时候提出了一个问题。这只是使用命令式代码的原因之一。如果能成功就太好了;还有其他一些更具可维护性的替代方案。其中之一是声明性代码。重点是问你需要什么,而不是怎么去做。

In your particular case, this can look like the following. First, you need to find out what is it that you're looking for, that is, discover abstractions. In your case, it looks like you need a date. Not just any date, but the one having some standard representation. Say, ISO8601 date. There are at least two implementations: the first one is a date parsed from an ISO8601-formatted string (or a string in any other format actually), and the second is some future date which is a day later. Thus, the whole code could look like that:

(new Future(
    new DateTimeParsedFromISO8601('2009-09-30 20:24:00'),
    new OneDay()
))
    ->value();

要了解更多关于datetime杂耍的例子,请看这篇文章。

其他回答

我总是加86400秒(一天):

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

echo 'date after adding 1 day: '.$stop_date; 

这可能不是你能做到的最巧妙的方法,但它是有效的!

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

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

下面的代码使用DateTime类及其方法modify()和format()获得当年1月的第一天(但可以是另一个日期),并在这一天上添加365天(但可以是N天):

echo (new DateTime((new DateTime())->modify('first day of January this year')->format('Y-m-d')))->modify('+365 days')->format('Y-m-d');
<?php
$stop_date = '2009-09-30 20:24:00';
echo 'date before day adding: ' . $stop_date; 
$stop_date = date('Y-m-d H:i:s', strtotime($stop_date . ' +1 day'));
echo 'date after adding 1 day: ' . $stop_date;
?>

对于PHP 5.2.0+,你也可以这样做:

$stop_date = new DateTime('2009-09-30 20:24:00');
echo 'date before day adding: ' . $stop_date->format('Y-m-d H:i:s'); 
$stop_date->modify('+1 day');
echo 'date after adding 1 day: ' . $stop_date->format('Y-m-d H:i:s');

这招对我很管用: 当前日期

$date = date('Y-m-d', strtotime("+1 day"));

anydate:

date('Y-m-d', strtotime("+1 day", strtotime($date)));