2013-11-24 5 views
-2

분 단위 만 인쇄하도록이 기능을 어떻게 변경할 수 있습니까?일,시, 분, 초로 시간 소인

내 말입니다 :

지금 당장

This was 7 second ago 
-- Couple minutes later -- 
This was 5 minute 8 second ago 

입니다하지만 난이 원하는 : 그 복수의 경우에도

This was 7 second ago 
-- Couple minutes later -- 
This was 5 minute ago (i dont care about the seconds) 

어떻게 확인할 수 있을까? 그러면 광고 단위 뒤에 S가 표시됩니까?

기능 :

function humanTiming($time) 
{ 
$time = time() - $time; // to get the time since that moment 

$tokens = array (
    31536000 => 'year', 
    2592000 => 'month', 
    604800 => 'week', 
    86400 => 'day', 
    3600 => 'hour', 
    60 => 'minute', 
    1 => 'second' 
); 

$result = ''; 
$counter = 1; 
foreach ($tokens as $unit => $text) { 
    if ($time < $unit) continue; 
    if ($counter > 2) break; 

    $numberOfUnits = floor($time/$unit); 
    $result .= "$numberOfUnits $text "; 
    $time -= $numberOfUnits * $unit; 
    ++$counter; 
} 

return "This was {$result} ago"; 
} 

답변

3

에 대한 해결책이 될 수 있습니다 여기에 (Glavić's answer here에서 촬영 기능) DateTime 클래스를 사용하여 한 가지 방법이있다 :

function human_timing($datetime, $full = false) { 
    $now = new DateTime; 
    $ago = new DateTime('@'.$datetime); 
    $diff = $now->diff($ago); 

    $diff->w = floor($diff->d/7); 
    $diff->d -= $diff->w * 7; 

    $string = array(
     'y' => 'year', 
     'm' => 'month', 
     'w' => 'week', 
     'd' => 'day', 
     'h' => 'hour', 
     'i' => 'minute', 
     's' => 'second', 
    ); 
    foreach ($string as $k => &$v) { 
     if ($diff->$k) { 
      $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : ''); 
     } else { 
      unset($string[$k]); 
     } 
    } 

    if (!$full) $string = array_slice($string, 0, 1); 
    return $string ? implode(', ', $string) . ' ago' : 'just now'; 
} 
,

예 :

echo human_timing(time() - 20); 
echo human_timing(time() - 1000); 
echo human_timing(time() - 5500); 

출력 :

20 seconds ago 
16 minutes ago 
1 hour ago 

Demo

1

체크 아웃 PHP Date Time 클래스, 당신은이를 사용하는 대신 수동으로 일을해야합니다.

0

$numberOfUnits = floor($time/$unit); 

If ((int) $numberOfUnits > 1) 
{ 
    $text .= 's'; 
} 

은이

$numberOfUnits = floor($time/$unit); 

를 교체 그것은 복수

관련 문제