计算PHP中两个日期之间的月数?

cro*_*lee 22 php date

如果不使用PHP 5.3的date_diff功能(我使用PHP 5.2.17),有一个简单而准确的方法来做到这一点?我正在考虑类似下面的代码,但我不知道如何解释闰年:

$days = ceil(abs( strtotime('2000-01-25') - strtotime('2010-02-20') ) / 86400);
$months = ???;
Run Code Online (Sandbox Code Playgroud)

我想弄清楚一个人的月龄.

dec*_*eze 77

$date1 = '2000-01-25';
$date2 = '2010-02-20';

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);

$month1 = date('m', $ts1);
$month2 = date('m', $ts2);

$diff = (($year2 - $year1) * 12) + ($month2 - $month1);
Run Code Online (Sandbox Code Playgroud)

您可能希望将日期也包括在内,具体取决于您是否意味着月.希望你能得到这个想法.


pol*_*1er 15

这是我在班上写的一个简单方法,用于计算两个给定日期所涉及的月数:

public function nb_mois($date1, $date2)
{
    $begin = new DateTime( $date1 );
    $end = new DateTime( $date2 );
    $end = $end->modify( '+1 month' );

    $interval = DateInterval::createFromDateString('1 month');

    $period = new DatePeriod($begin, $interval, $end);
    $counter = 0;
    foreach($period as $dt) {
        $counter++;
    }

    return $counter;
}
Run Code Online (Sandbox Code Playgroud)

  • 不用在周期内循环,您可以简单地使用`iterator_count($ period)` (4认同)

小智 13

这是我的解决方案。它检查日期的年份和月份并找出差异。

 $date1 = '2000-01-25';
 $date2 = '2010-02-20';
 $d1=new DateTime($date2); 
 $d2=new DateTime($date1);                                  
 $Months = $d2->diff($d1); 
 $howeverManyMonths = (($Months->y) * 12) + ($Months->m);
Run Code Online (Sandbox Code Playgroud)