很长一段时间以来,我一直在与time ago函数作斗争。基本上,我使用日期timestamp将帖子/评论存储在mysql数据库中。稍后,我想显示添加的时间,例如53 minutes ago。
我将用户时区存储到mysql db中,并希望使用用户的时区显示此time ago函数。
但是,我的函数返回错误的值,例如,我生活在UTC +2,在我的国家时间是11:54。如果我添加新的post,并检查db,post添加的时间是11:54,但是当我想显示时间之前(需要10秒前)时,它会显示添加的1 hour, 59 minutes, 50 seconds ago并像1 hour, 56 minutes, 26 seconds ago一样下降。

得到时区函数
if(isset($userRow['timezone'])) {
date_default_timezone_set($userRow['timezone']);
}elseif(isset($_COOKIE['timeZone'])) {
date_default_timezone_set($_COOKIE['timeZone']);
}调用time_elapsed函数
<?php echo $user->time_elapsed($datevariable); ?>time_elapsed函数
function time_elapsed($datetime, $full = 7) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
echo "</br>";
echo "echo db timestamp for test: ";
echo $datetime;
echo "</br>";
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}发布于 2017-12-21 10:45:37
可能发生的情况是,PHP使用的是默认时区,保存在php.ini文件date.timezone中。您可以使用phpinfo();看到它,并查找date.timezone。你可能需要在那里改变它。
可用时区,以备需要:PHP时区
https://stackoverflow.com/questions/47922474
复制相似问题