Have a Snippet?

Keep, track and share your code snippets with your friends



PHP: Convert the timestamp to human-readable format Share on Vkontakte

Convert the timestamp to human-readable format like XX minutes ago or XX days ago. Was found here: http://stackoverflow.com/questions/2915864/php-how-to-find-the-time-elapsed-since-a-date-time

function humanTiming ($time)
{
        $time = strtotime($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'
    );

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

}

$time = '2013-05-25 15:45:22';
echo 'Event happened '.humanTiming($time);


Tag: PHP, readable, DateTime, Date Routines

0 Comments