【发布时间】:2010-12-12 07:38:43
【问题描述】:
对于 UNIX 时间戳差异,是否有任何漂亮的打印库。诸如“x 分钟前”、“x 小时前”、“x 天前”等社交网站上看到的东西之类的东西。我知道自己写并不难,但为什么要重新发明轮子呢?
【问题讨论】:
对于 UNIX 时间戳差异,是否有任何漂亮的打印库。诸如“x 分钟前”、“x 小时前”、“x 天前”等社交网站上看到的东西之类的东西。我知道自己写并不难,但为什么要重新发明轮子呢?
【问题讨论】:
试试
<?php
function rel_time($from, $to = null)
{
$to = (($to === null) ? (time()) : ($to));
$to = ((is_int($to)) ? ($to) : (strtotime($to)));
$from = ((is_int($from)) ? ($from) : (strtotime($from)));
$units = array
(
"year" => 29030400, // seconds in a year (12 months)
"month" => 2419200, // seconds in a month (4 weeks)
"week" => 604800, // seconds in a week (7 days)
"day" => 86400, // seconds in a day (24 hours)
"hour" => 3600, // seconds in an hour (60 minutes)
"minute" => 60, // seconds in a minute (60 seconds)
"second" => 1 // 1 second
);
$diff = abs($from - $to);
$suffix = (($from > $to) ? ("from now") : ("ago"));
foreach($units as $unit => $mult)
if($diff >= $mult)
{
$and = (($mult != 1) ? ("") : ("and "));
$output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
$diff -= intval($diff / $mult) * $mult;
}
$output .= " ".$suffix;
$output = substr($output, strlen(", "));
return $output;
}
?>
【讨论】:
我不知道是否有针对此的 PHP 库,但 Jeff(创建此网站的人)很久以前就问过这个问题。有关详细信息,请参阅this question。我相信你可以从中得到很多启发。 Jeff 甚至用the code they use on StackOverflow itself 回答了这个问题。
我不认为自己写这篇文章有那么难,所以为什么不花 5 分钟写它而不是花半小时寻找图书馆呢?
【讨论】:
【讨论】:
defined('SECOND') ? NULL : define('SECOND', 1);
defined('MINUTE') ? NULL : define('MINUTE', 60 * SECOND);
defined('HOUR') ? NULL : define('HOUR', 60 * MINUTE);
defined('DAY') ? NULL : define('DAY', 24 * HOUR);
defined('MONTH') ? NULL : define('MONTH', 30 * DAY);
defined('YEAR') ? NULL : define('YEAR', 12 * MONTH);
class Time{
public $td;
public function set_td($timestamp){
$this->td = time() - $timestamp;
}
public function string_time($timestamp){
$this->set_td($timestamp);
if ($this->td < 0){
return "not yet";
}
if ($this->td < 1 * MINUTE){
return $this->td <= 1 ? "just now" : $this->td." seconds ago";
}
if ($this->td < 2 * MINUTE){
return "a minute ago";
}
if ($this->td < 45 * MINUTE){
return floor($this->td / MINUTE)." minutes ago";
}
if ($this->td < 90 * MINUTE){
return "an hour ago";
}
if ($this->td < 24 * HOUR){
return floor($this->td / HOUR)." hours ago";
}
if ($this->td < 48 * HOUR){
return "yesterday";
}
if ($this->td < 30 * DAY){
return floor($this->td / DAY)." days ago";
}
if ($this->td < 12 * MONTH){
$months = floor($this->td / MONTH);
return $months <= 1 ? "one month ago" : $months." months ago";
}else{
$years = floor($this->td / YEAR);
return $years <= 1 ? "one year ago" : $years." years ago";
}
}
}
$time = new Time();
只需将您的时间戳放入新对象并以秒为单位接收时间差异。例如
$string = $time->string_time($timestamp);
【讨论】: