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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答