doushui3216 2015-11-17 22:46
浏览 40
已采纳

获得两个日期之间的数月差异

I am doing a comparasion between two dates and trying to get the year and month difference between those two dates (not the day itself).

$d1 = strtotime("2012-12");
$d2 = strtotime("2014-03");
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$i = 0;

while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
    $i++;
}

echo $i;

This outputs 15 months but how would i go about converting that into months and years?

Or if there is a better way of handling this - would love to know

  • 写回答

1条回答 默认 最新

  • duanbi9202 2015-11-17 22:52
    关注

    you can create DateTime objects and invoke diff:

    $date1 = new DateTime("2012-12");
    $date2 = new DateTime("2014-03");
    $interval = $date1->diff($date2);
    echo $interval->y . " years, " . $interval->m." months, ".$interval->d." days"; 
    

    spits out:

    1 years, 3 months, 0 days
    

    and if you REALLY have your heart set on using strtotime, you can get the difference in seconds like so:

    $one_hour = 30*60*60;
    $one_day = 24*$one_hour;
    $one_month = 30*$one_day;
    $one_year = 365*$one_day;
    
    $diff = abs(strtotime('2012-12') - strtotime('2014-03'));
    $years = floor($diff / $one_year);
    $months = floor(($diff - $years * $one_year) / $one_month);
    $days = floor(($diff - $years * $one_year - $months*$one_month)/ $one_day);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?