将一天添加到日期的代码返回日期之前的日期:
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杂耍的例子,请看这篇文章。