human_time_diff()
仅返回单个{number} {unit}
向后串。它四舍五入到最接近的整个单位,而不是精确地分解差异。
要获得精确的持续时间差,您需要使用自己的函数。由于这是PHP中的一个热门需求,因此在线上有很多解决方案-here\'s a clever one 我发现:
$t1 = "Jan 08 2018 07:45:14";
$t2 = "Jan 08 2018 09:15:44";
echo time_elapsed_string($t1,$t2);
function time_elapsed_string($datetime,$datetime2, $full = true) {
$now = new DateTime($datetime2);
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$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\';
}
这将为您提供:
1 hour, 30 minutes, 30 seconds ago