【发布时间】:2015-04-03 23:26:20
【问题描述】:
考虑到某些月份的天数比其他月份少,我正在使用我发现的 here 函数将月份添加到日期中。
function addMonths($date_str, $months){
$date = new DateTime($date_str);
$start_day = $date->format('j');
var_dump($date->format('Y-m-d'));
$date->modify("+{$months} month");
$end_day = $date->format('j');
var_dump($date->format('Y-m-d'));
if ($start_day != $end_day)
$date->modify('last day of last month');
var_dump($date->format('Y-m-d'));die();
return $date->format('Y-m-d');
}
由于该函数未按预期工作,因此我转储了一些变量以查看发生了什么。让我们尝试以下方法:
addMonths('2012-05-31',1)
我得到以下错误输出:
string(10) "2012-05-31" string(10) "2012-07-01" string(10) "2012-05-31"
正如您所见,当我在输入日期中添加一个月时,我得到“2012-07-01”,但随后满足条件,我应该得到 6 月的最后一天,即 7 月的前一个月,而不是 5 月。我不知道发生了什么,你能帮帮我吗?
【问题讨论】:
-
您使用哪个 php 版本?最后一个转储为我返回
2012-06-30。 -
5.2.9,AFAIK修改方法适用于这个版本