我有这个时间戳PHP代码,它没有显示正确的时间.它总是显示8小时前,当时间假设是几分钟前.
/**
* Convert a timestap into timeago format
* @param time
* @return timeago
*/
public static function timeago($time, $tense = "ago"){
if(empty($time)) return "n/a";
$time=strtotime($time);
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
$now = time();
$difference = $now - $time;
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
if($difference != 1) {
$periods[$j].= "s";
}
return "$difference $periods[$j] $tense ";
} Run Code Online (Sandbox Code Playgroud)
我真的不明白为什么它不能正常工作
小智 7
这是我为你写的一个功能.
它使用DateTime类,因此PHP版本必须> = 5.3.0.
阅读函数中的注释以了解其工作原理.
function timeago($time, $tense='ago') {
// declaring periods as static function var for future use
static $periods = array('year', 'month', 'day', 'hour', 'minute', 'second');
// checking time format
if(!(strtotime($time)>0)) {
return trigger_error("Wrong time format: '$time'", E_USER_ERROR);
}
// getting diff between now and time
$now = new DateTime('now');
$time = new DateTime($time);
$diff = $now->diff($time)->format('%y %m %d %h %i %s');
// combining diff with periods
$diff = explode(' ', $diff);
$diff = array_combine($periods, $diff);
// filtering zero periods from diff
$diff = array_filter($diff);
// getting first period and value
$period = key($diff);
$value = current($diff);
// if input time was equal now, value will be 0, so checking it
if(!$value) {
$period = 'seconds';
$value = 0;
} else {
// converting days to weeks
if($period=='day' && $value>=7) {
$period = 'week';
$value = floor($value/7);
}
// adding 's' to period for human readability
if($value>1) {
$period .= 's';
}
}
// returning timeago
return "$value $period $tense";
}
Run Code Online (Sandbox Code Playgroud)
不要忘记设置你工作的时区
date_default_timezone_set('UTC');
Run Code Online (Sandbox Code Playgroud)
用它
echo timeago('1981-06-07'); // 34 years ago
echo timeago(date('Y-m-d H:i:s')); // 0 seconds ago
Run Code Online (Sandbox Code Playgroud)
等等