0

I found a function form SC to output human readable time. like `

5 hours, 1 hour, 5 years, etc

function human_time ($time)
{

    $time = time() - strtotime($time); // to get the time since that moment
    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );

    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
    }

}

And I have time as string: 2013-09-28 20:55:42

when I call this function human_time('2013-09-28 20:55:42')

then it return nothing, why ? I have added strtotime in above function.

Please tell me what is wrong.

user007
  • 3,203
  • 13
  • 46
  • 77
  • 2
    Have you considered using php's `DateTime` class for your purpose? I guess there's no need to reinvent the wheel here. – TheWolf Sep 28 '13 at 15:38
  • I tried to search on google, and I found this function on stackoverflow, please suggest if there is already a function – user007 Sep 28 '13 at 15:39
  • 1
    Is this of any use to you? https://github.com/vascowhite/TimeAgo it will at least show you one way of doing it. – vascowhite Sep 28 '13 at 15:51
  • Take a look at [this simple function](http://stackoverflow.com/a/18602474/67332). – Glavić Sep 29 '13 at 22:33

2 Answers2

1

This is no ready-to-use code, but rather supposed to guide you the right way:

$then = new DateTime($time); // you might need to format $time using strtotime or other functions depending on the format provided
$now = new DateTime();
$diff = $then->diff($now, true);
echo $diff->format('Your style goes here');

See DateTime Manual for further documentation or feel free to ask here.

Edit: Link fixed.

TheWolf
  • 1,385
  • 7
  • 16
1

Use example :

echo time_elapsed_string('2013-05-01 00:22:35');
echo time_elapsed_string('2013-05-01 00:22:35', true);

Output :

4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago

Link to the function.

Community
  • 1
  • 1
Glavić
  • 42,781
  • 13
  • 77
  • 107