显示“时间之前”而不是PHP Codeigniter中的datetime [英] Display "time ago" instead of datetime in PHP Codeigniter
问题描述
我想显示一个类似twitter和FB的时间格式(发布于3小时前,发表于2分钟前,等等...)
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;
}
}
我用这个函数回调到另一个函数, :$ this-> format_interval();并将其传递给我的视图
I use this function with a callback into another function like : $this->format_interval(); and pass it to my View
我当前的格式日期是: 2012-07-26 09:31:pm 并已存储在我的数据库
My current format date is : 2012-07-26 09:31:pm and already stored in my DB
任何帮助将非常感激!
推荐答案
日期助手 timespan()
方法只是这样做:
此功能最常用的目的是显示从某个时间点到
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年,10个月,2周,5天,10小时,16分钟
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';
这篇关于显示“时间之前”而不是PHP Codeigniter中的datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!