Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
905 views
in Technique[技术] by (71.8m points)

date - Display "time ago" instead of datetime in PHP Codeigniter

I would like to display a time format like twitter and FB (Posted 3 hours ago, Posted 2 minutes ago and so on...)

I've tried this piece of code without success :

function format_interval($timestamp, $granularity = 2) {
  $units = array('1 year|@count years' => 31536000, '1 week|@count weeks' => 604800, '1 day|@count days' => 86400, '1 hour|@count hours' => 3600, '1 min|@count min' => 60, '1 sec|@count sec' => 1);
  $output = '';
  foreach ($units as $key => $value) {
    $key = explode('|', $key);
    if ($timestamp >= $value) {
      $floor = floor($timestamp / $value);
      $output .= ($output ? ' ' : '') . ($floor == 1 ? $key[0] : str_replace('@count', $floor, $key[1]));
      $timestamp %= $value;
      $granularity--;
    }

    if ($granularity == 0) {
      break;
    }
}

I use this function with a callback into another function like : $this->format_interval(); and pass it to my View

My current format date is : 2012-07-26 09:31:pm and already stored in my DB

Any help will be very appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Date Helper's timespan() method just does that:

The most common purpose for this function is to show how much time has elapsed from some point in time in the past to now.

Given a timestamp, it will show how much time has elapsed in this format:

1 Year, 10 Months, 2 Weeks, 5 Days, 10 Hours, 16 Minutes

So, in your example, all you need to do is convert your date to a timestamp and do something like this:

$post_date = '13436714242';
$now = time();

// will echo "2 hours ago" (at the time of this post)
echo timespan($post_date, $now) . ' ago';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...