2014-09-01 22 views
0

我想兩個日期時間之間的區別,因此,如果不同的是幾秒鐘,我只想等呼應秒,例如輸出應該是這樣的:如何區分所有單位(y,m,d,h,i,s)中的兩個日期時間?

5 seconds ago

5 minutes ago

5 hours ago ...

這裏是我的代碼,我使用的,但它給我的只有天:

$date1 = new DateTime(date('Y-m-d', strtotime("2013-08-07 13:00:00"))); 
$date2 = new DateTime(date('Y-m-d', strtotime("2012-08-08 12:00:00"))); 
echo $date1->diff($date2)->days; 

這個代碼是給我我想要什麼,但一下子:

$x = new DateTime($career->postdate); 
$interval = $x->diff(new DateTime(date('Y-m-d H:i:s'))); 
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %S seconds'); 
echo $elapsed; 

我知道我可以在第二代碼的輸出中串發揮達到我的目標,但它不是一個首選方式,所以我怎麼能以最好的方式做到這一點?

+0

http://stackoverflow.com/questions/10696654/get-total-time-difference-間兩日期,使用的PHP – 2014-09-01 17:26:41

回答

2
function x($i, $s) { 
    return ($i>0 ? $i.$s : ""); 
} 

function f($int) { 
    $ret = x($int->y, 'y '); 
    $ret.= x($int->m, 'm '); 
    $ret.= x($int->d, 'd '); 
    $ret.= x($int->h, 'h '); 
    $ret.= x($int->i, 'min '); 
    $ret.= x($int->s, 's '); 
    return $ret; 
} 

$date1 = new DateTime("2013-08-08 13:00:00"); 
$date2 = new DateTime("2012-08-06 12:30:00"); 
$interval = $date1->diff($date2); 
echo f($interval); 
0

這是我如何解決它的處理方法的輸出()函數:

      $x = new DateTime($career->postdate); 
          $interval = $x->diff(new DateTime(date('Y-m-d H:i:s'))); 
          $elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %S seconds'); 
          if($interval->format('%y') !=0){ 

           if($interval->format('%m') !=0){ 

            echo $interval->format('%y years %m months ago.'); 
           } 
           else{ 

            echo $interval->format('%y years ago.'); 
           }  
          } 

          elseif($interval->format('%m') !=0){ 

           if($interval->format('%a') !=0){ 

            echo $interval->format('%m months %a days ago.'); 
           } 
           else{ 

            echo $interval->format('%m months ago.'); 
           } 
          } 

          elseif($interval->format('%d') !=0){ 

           if($interval->format('%h') !=0){ 

            echo $interval->format('%a days %h hours ago.'); 
           } 
           else{ 

            echo $interval->format('%a days ago.'); 
           } 
          } 

          elseif($interval->format('%h') !=0){ 

           if($interval->format('%i') !=0){ 

            echo $interval->format('%h hours %i minutes ago.'); 
           } 
           else{ 

            echo $interval->format('%h hours ago.'); 
           } 
          } 

          elseif($interval->format('%i') !=0){ 

           if($interval->format('%S') !=0){ 

            echo $interval->format('%i minutes %S seconds ago.'); 
           } 
           else{ 

            echo $interval->format('%i minutes ago.'); 
           } 
          } 

          elseif($interval->format('%S') !=0){ 

           echo $interval->format('%S seconds ago.'); 
          } 
相關問題