cweiske
cweiske

Reputation: 31078

PHP library to generate user friendly relative timestamps

I'm looking for a PHP library that generates user-friendly representations of times - for example "two hours ago" when the timestamp is time() - 2 * 3600.

There are several existing questions with answers and blog posts (1, 2, 3), but all only contain code snippets - not a library I can install and upgrade.

Django has one, Python also has a standalone lib, Javascript has several (1, 2, 3), too - where is the PHP library?


A library should have the following things:

Upvotes: 10

Views: 1717

Answers (4)

LHolleman
LHolleman

Reputation: 2596

I know Kohana has one, you can propably port it easily.

The function is called fuzzy_span().

See http://kohanaframework.org/3.3/guide-api/Date#fuzzy_span

Upvotes: 3

Ashim Saha
Ashim Saha

Reputation: 162

Try this code:

$current_date_time_get_updated_on_date_format = '';

function get_updated_on_date_format($dt_updated, $prefix = 'Updated ', $at = 'at ') {
    global $current_date_time_get_updated_on_date_format;

    if ($current_date_time_get_updated_on_date_format == '') {
        $current_date_time_get_updated_on_date_format = now();
    }

    $i_second_now         = strtotime($current_date_time_get_updated_on_date_format);
    $i_second_dt_updated  = strtotime($dt_updated);
    $i_second_diff        = $i_second_now - $i_second_dt_updated;
    $s_return_date_format = '';

    if ($i_second_diff < 0) {
        // Developers Uploading Time, Time Zone Gap Patch
        $s_return_date_format = $prefix . $at . date('g:ia \o\n F jS, Y', strtotime($dt_updated));
    } else if ($i_second_diff < 60) {
        $s_return_date_format = $prefix . $i_second_diff . ' seconds ago ';
    } elseif ($i_second_diff < (60 * 60)) {
        $s_return_date_format = $prefix . round(($i_second_diff / 60), 0) . ' minitues ago ';
    } elseif ($i_second_diff < (60 * 60 * 24)) {
        $s_return_date_format = $prefix . round(($i_second_diff / (60 * 60)), 0) . ' hours ago ';
    } else {
        $s_return_date_format = $prefix . $at . date('g:ia \o\n F jS, Y', strtotime($dt_updated));
    }

    return $s_return_date_format;

}

function now() {
    // it should extract database time in this format 'YYYY-MM-DD HH:MM:SS'
    return mysql_now_value;
}

Upvotes: 0

cweiske
cweiske

Reputation: 31078

Since there didn't seem to be any library, I've made one myself and got it included in PEAR:

Date_HumanDiff, http://pear.php.net/package/Date_HumanDiff

Code is at http://github.com/pear/Date_HumanDiff

Upvotes: 7

s.webbandit
s.webbandit

Reputation: 17000

Kohana Date class provides fuzzy_span() method for this. But it can't reply you exact values like "10 minutes"

Upvotes: 1

Related Questions