我想显示像twitter和FB这样的时间格式(发布时间3小时前,发布2分钟前等等…)
我试过这段代码没有成功:
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();并将其传递给我的视图
我目前的格式日期是:2012-07-26 09:31:pm并且已存储在我的数据库中
任何帮助将非常感谢!
Date Helper’s 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.
给定时间戳,它将显示此格式已经过了多长时间:
1 Year,10 Months,2 Weeks,5 Days,10 Hours,16 Minutes
因此,在您的示例中,您需要做的就是将日期转换为时间戳并执行以下操作:
$post_date = '13436714242'; $now = time(); // will echo "2 hours ago" (at the time of this post) echo timespan($post_date,$now) . ' ago';