2017-05-10 90 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); 

?>