tags:

views:

36

answers:

3

Hi, i want a php function to convert a unix time stamp to like this:

15 seconds

or

45 minutes

or

3 hours

and not like this : 2seconds, 5minutes, 9 hours

i want only one value like digg ( made popular xx xxxxx )

Thanks

A: 

PHP doesn't have a built-in function to do it for you, so you'd have to do it by hand. This function will get the difference in days, hours, minutes, or seconds and return in the format 'X days/hours/minutes/seconds':

<?php
function GetTimeDiff($timestamp) {
    $how_log_ago = '';
    $seconds = time() - $timestamp; 
    $minutes = (int)($seconds / 60);
    $hours = (int)($minutes / 60);
    $days = (int)($hours / 24);
    if ($days >= 1) {
      $how_log_ago = $days . ' day' . ($days != 1 ? 's' : '');
    } else if ($hours >= 1) {
      $how_log_ago = $hours . ' hour' . ($hours != 1 ? 's' : '');
    } else if ($minutes >= 1) {
      $how_log_ago = $minutes . ' minute' . ($minutes != 1 ? 's' : '');
    } else {
      $how_log_ago = $seconds . ' second' . ($seconds != 1 ? 's' : '');
    }
    return $how_log_ago;
?>
Parrots
+1  A: 

If this is for a website, you might consider Timeago. Otherwise the algorithm is pretty straightforward. Something like:

$diff = $date - $now;
if ($diff > 2 * ONE_YEAR)
    return sprintf("%d years", round($diff / ONE_YEAR));
else if ($diff > ONE_YEAR)
    return "1 year";
else if ($diff > 2 * ONE_MONTH)
    return sprintf("%d months", round($diff / ONE_MONTH));
...etc...
FryGuy
+2  A: 

Try this:

function toFriendlyTime($seconds) {
  $measures = array(
    'day'=>24*60*60,
    'hour'=>60*60,
    'minute'=>60,
    'second'=>1,
    );
  foreach ($measures as $label=>$amount) {
    if ($seconds >= $amount) {  
      $howMany = floor($seconds / $amount);
      return $howMany." ".$label.($howMany > 1 ? "s" : "");
    }
  } 
  return "now";
}   

As you can see, it's also flexible for adding/removing measures of time as you see fit. Just be sure to order the measures from largest to smallest. A test:

print(                           
    toFriendlyTime(0)."\n"           
    .toFriendlyTime(1)."\n"          
    .toFriendlyTime(2)."\n"          
    .toFriendlyTime(60)."\n"         
    .toFriendlyTime(3600)."\n"   
    .toFriendlyTime(24*3600)."\n"                                               
    );

Results in:

now
1 second
2 seconds
1 minute
1 hour
1 day
Lucas Oman