我有这个时间戳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 ";
}
我真的不明白为什么它不能正常工作
答案 0 :(得分:7)
这是我为你写的一个功能。
它使用DateTime class,因此PHP版本必须是&gt; = 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";
}
不要忘记设置你工作的时区
date_default_timezone_set('UTC');
使用它
echo timeago('1981-06-07'); // 34 years ago
echo timeago(date('Y-m-d H:i:s')); // 0 seconds ago
等
答案 1 :(得分:1)
可能你的时区设置不正确!在抽出时间之前,请尝试设置默认时区:
date_default_timezone_set ( string $timezone_identifier )
答案 2 :(得分:0)
function time_elapsed($datetime, $full = false) {
$now = time();
$ago = strtotime($datetime);
$diff = $now - $ago;
$string = array(
'year' => 31104000,
'month' => 2592000,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute'=> 60,
'second'=> 1
);
$data = array();
foreach ($string as $k => $v) {
if($diff > $v){
$count = round($diff / $v);
$data[$k] = $count . (($count > 1) ? ' ' . $k .'s' : ' ' . $k);
$diff = $diff % $v;
}
}
if (!$full) $data = array_slice($data, 0, 1);
return $data ? implode(', ', $data) . ' ago' : 'just now';
}
echo time_elapsed('2016-01-18 13:07:30', true);
// 2 years, 1 month, 2 weeks, 6 days, 25 seconds ago
echo time_elapsed('2016-01-18 13:07:30');
// 2 years ago