user007
user007

Reputation: 3243

PHP - subtracting time return nothing

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.

Upvotes: 0

Views: 77

Answers (2)

Glavić
Glavić

Reputation: 43582

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.

Upvotes: 1

TheWolf
TheWolf

Reputation: 1385

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.

Upvotes: 1

Related Questions