Yaz's Blog

I am a php developer. I am a geek. I am a fiction reader. A movie and tv addict.
An XBOX360 player. A snowboarder. A cyclist. A Softball player. A Venezuelan-Canadian.

Timeago

marco:

matthewb:

Great little jQuery plugin by Ryan McGeary to display ISO 8601 date and time strings as plain-English “fuzzy” timestamps like those used on Tumblr (eg, “posted 1 day ago”). (via Script & Style)

Aw, I didn’t know anyone cared so much. Here’s the PHP function:

function pretty_timespan($seconds)
{
    $seconds = intval($seconds);

    if ($seconds == 0) {
        return 'now';
    } else if ($seconds < 0) {
        $pre     = '';
        $post    = ' ago';
        $seconds = 0 - $seconds;
    } else {
        $pre     = 'In ';
        $post    = '';
    }

    $units = array(31536000 => 'year',
                   2592000  => 'month',
                   604800   => 'week',
                   86400    => 'day',
                   3600     => 'hour',
                   60       => 'minute',
                   1        => 'second');

    foreach ($units as $max => $unit) {
        if ($seconds < $max) continue;
        $num = floor($seconds / $max);
        return $pre . pluralize($num, $unit) . $post;
    }
}

And the pluralize function it depends on:

function pluralize($number, $noun, $nouns = false)
{
    if (! $nouns) $nouns = $noun . 's';
    return $number . ' ' . ($number == 1 ? $noun : $nouns);
}

That jQuery version is better because it’s immune to long cache times, but this might be useful if you want to output it without using Javascript.

Ohhhhhhhhh genious. Thanks! :D

Blog comments powered by Disqus