我正在使用我在这里找到的一个函数来添加月份到日期,考虑到某些月份的天数比其他月份少。
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 在
PHP 5.2.17 之前有一个 DateTime 相对格式的错误
试试这个:
<?php
function addMonths($date_str, $months) {
$date = new DateTime($date_str);
$start_day = $date->format('j');
$date->modify("+{$months} month");
$end_day = $date->format('j');
if ($start_day != $end_day) {
$date->modify('last day');
}
return $date->format('Y-m-d');
}
echo addMonths('2012-05-31', 1);
我这里没有这么旧的PHP,但我认为它可以处理这个版本中的last day
。
对我来说,它返回:
2012-06-30
我复制/粘贴了您的代码,以下是我在 PHP 5.3.3 上的输出:
string(10) "2012-05-31"
string(10) "2012-07-01"
string(10) "2012-06-30"
function add_month($format , $date , $months_to_add ){
return date($format, strtotime("$date +$months_to_add month"));
}
我正在使用这个。你可以试试这个。