是否有适用于UNIX时间戳差异的漂亮的漂亮打印库。社交网站上看到的东西,比如“x分钟前”,“x小时前”,“x天前”等等。我知道自己写作并不难写,但为什么重新发明轮子呢?
答案 0 :(得分:2)
试
<?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;
}
?>
答案 1 :(得分:1)
我不知道是否有用于此的PHP库,但Jeff(创建此网站的人)很久以前就问过这个问题。有关详细信息,请参阅this question。我相信你可以从中获得很多灵感。杰夫甚至用the code they use on StackOverflow itself回答了这个问题。
我认为自己写这篇文章并不难,所以为什么不花5分钟写一下而不是半小时寻找一个图书馆呢?
答案 2 :(得分:0)
答案 3 :(得分:0)
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);