3

我正在尝试将两个日期之间的差异转换为总年数,现在我正在使用这个:

 $datetime1 = new DateTime('2009-10-11'); 
 $datetime2 = new DateTime('2010-10-10');
 $interval = $datetime1->diff($datetime2);
 return $interval->format('%y');

这会返回一个 int(例如 0 表示 < 一年,2 表示两年等)

我需要结果为十进制,如下所示:

0.9 - 9 个月

1.2 - 1年零两个月

3.5 - 3年零5个月

等等..

谢谢!

4

3 回答 3

5

如果您不关心完美的准确性:

return $interval->days / 365;

你也可以做类似的事情return $interval->y + $interval->m / 12 + $interval->d / 365

在我看到@2unco 的评论之前,我什至没有注意到你奇怪的十进制约定。那看起来像:return $interval->y . '.' . $interval->m.

于 2012-05-28T01:01:01.037 回答
2

在这里,您可以看到一个完全可以做到这一点的函数,并且有很多选项: http: //php.net/manual/es/function.date-diff.php#98615

    <?php 
/* 
* A mathematical decimal difference between two informed dates 
*
* Author: Sergio Abreu
* Website: http://sites.sitesbr.net
*
* Features: 
* Automatic conversion on dates informed as string.
* Possibility of absolute values (always +) or relative (-/+)
*/

function s_datediff( $str_interval, $dt_menor, $dt_maior, $relative=false){

       if( is_string( $dt_menor)) $dt_menor = date_create( $dt_menor);
       if( is_string( $dt_maior)) $dt_maior = date_create( $dt_maior);

       $diff = date_diff( $dt_menor, $dt_maior, ! $relative);

       switch( $str_interval){
           case "y": 
               $total = $diff->y + $diff->m / 12 + $diff->d / 365.25; break;
           case "m":
               $total= $diff->y * 12 + $diff->m + $diff->d/30 + $diff->h / 24;
               break;
           case "d":
               $total = $diff->y * 365.25 + $diff->m * 30 + $diff->d + $diff->h/24 + $diff->i / 60;
               break;
           case "h": 
               $total = ($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h + $diff->i/60;
               break;
           case "i": 
               $total = (($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i + $diff->s/60;
               break;
           case "s": 
               $total = ((($diff->y * 365.25 + $diff->m * 30 + $diff->d) * 24 + $diff->h) * 60 + $diff->i)*60 + $diff->s;
               break;
          }
       if( $diff->invert)
               return -1 * $total;
       else    return $total;
   }

/* Enjoy and feedback me ;-) */
?>
于 2016-12-05T16:16:14.590 回答
1

更简单、更准确的间隔转换器到天/小时/分钟/秒:

function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
    $nInterval = strtotime($sDate2) - strtotime($sDate1);
    if ($sUnit=='D') { // days
        $nInterval = $nInterval/60/60/24;
    } else if ($sUnit=='H') { // hours
        $nInterval = $nInterval/60/60;
    } else if ($sUnit=='M') { // minutes
        $nInterval = $nInterval/60;
    } else if ($sUnit=='S') { // seconds
    }
    return $nInterval;
} //DateDiffInterval
于 2017-06-01T22:14:30.757 回答