2017-05-10 91 views
0

我想創建活躍時間的用戶。在每隔1分鐘的時間內將更新數據庫。其中「$ dbtime」是在數據庫中更新的時間。這是我試過的代碼,但它只能計算正確的時間長達30分鐘。我正在努力創造一年。數據庫中保存的時間和當前時間格式相同。請幫我解決這個代碼。計算時間前在php

$now = new datetime('now'); 
    $current_time = $now->format('yjgis'); 

    $my_tim = $current_time - $dbtime; 

switch ($my_tim) { 
    case $my_tim < 60 && $my_tim > 0: 
     $a_tim = "Online"; 
     break; 
    case $my_tim > 60 && $my_tim < 3600 : 
     $a_tim = round($my_tim/60) .' '."Min ago"; 
     break; 
    case $my_tim > 3600 && $my_tim < 86400: 
     $a_tim = round(round($my_tim/60)/60).' '."Hour ago"; 
     break; 
    default: 
    $a_tim = "Offline"; 
} 
+0

並不積極,但'$ my_tim = $ CURRENT_TIME - $ DBTIME;'可能會更好是'$ my_tim = $ current_time-> sub($ dbtime);' –

+0

提供錯誤或意外收到。 –

回答

1

您可以使用此功能從CSS Tricks提取:

<?php 

function ago($time) 
{ 
    $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade"); 
    $lengths = array("60","60","24","7","4.35","12","10"); 

    $now = time(); 

    $difference  = $now - $time; 
    $tense   = "ago"; 

    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) { 
     $difference /= $lengths[$j]; 
    } 

    $difference = round($difference); 

    if($difference != 1) { 
     $periods[$j].= "s"; 
    } 

    return "$difference $periods[$j] 'ago' "; 
} 

echo ago($dbtime); 

?>