0

I'm building a WordPress plugin. I need to show time like Twitter - how much time ago the comment was made etc. Is there a way doing this?

Suppose someone comments 1 hour ago should be visible 1 hour ago and it should be precise to 1 second ago too.

0

Yes, you can do that using PHP.

Here's a function from @arnorhs:

$time = strtotime('2010-04-28 17:25:43');

echo 'event happened '.humanTiming($time).' ago';

function humanTiming ($time)
{

    $time = time() - $time; // to get the time since that moment
    $time = ($time<1)? 1 : $time;
    $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':'');
    }

}

WordPress' way

And actually there are many. But WordPress has a built-in function since its version 1.5.0 that would be handy for WordPress plugin development:

<?php human_time_diff( $from, $to ); ?>

Show comment's elapsed timing from now would be simple like:

echo human_time_diff( get_comment_time( 'U' ), current_time( 'timestamp' ) ) .' ago';

Reference:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.