如何计算两个日期之间的月数

时间:2012-12-19 07:51:32

标签: php datetime datediff

  

可能重复:
  How to calculate the difference between two dates using PHP?

enter image description here

$begintime=strtotime("2012-12-19");
$endtime=strtotime("2013-02-22");

结果应该是;

array(
array('text'=>'12/2012','days'=>13),
array('text'=>'01/2013','days'=>31)
array('text'=>'02/2013','days'=>22)
)

2 个答案:

答案 0 :(得分:4)

我更喜欢用面向对象的方法。

$begintime = new DateTime('2012-12-19'); // always use single quote whenever possible
$endtime = new DateTime('2013-01-22');
$time_interval = $endtime->diff($begintime); // in DateInterval object format

echo 'the time interval will be: ' . $time_interval->format('%d') . ' days';

要转换为您建议的数组格式,请自行处理。 (我认为不是问题的焦点)

答案 1 :(得分:3)

为了得到这些日子,试试这个:

$begintime = '2012-12-19';
$endtime = '2013-02-22';
$bd = new DateTime($begintime);
$ed = new DateTime($endtime);

$c = $bd->format('t') - $bd->format('d') + 1;
$pass = false;

while($bd->format('Y') < $ed->format('Y')
        || $bd->format('n') < $ed->format('n')) {
    $bd->modify("+1 month");
    echo $c." ";
    $c = $bd->format('t');
    $pass = true;
}
$c = $ed->format('d');
if(!$pass)
    $c -= $bd->format('d') - 1;
echo $c;

请参阅http://ideone.com/07wqkp

$bd->format('t')给出一个月内的最大天数。

ideone使用PHP 5.2.11。我想用PHP 5.4你可以使用

$bd->add(new DateInterval("P1M"));

而不是$bd->modify("+1 month");

编辑:修正了同一月份和年份开始和结束时的错误。

编辑: 恢复显式比较。第二个想法,没有if / else就更好了。