kyo*_*kyo 1 php unix datetime timestamp
我有一个以毫秒为单位的时间戳
$update = 1448895141168。
我正在努力将时间转换为人类可读的时间(ago)。
例如,1小时3分钟前。
我尝试在控制器中使用此功能
public function time_elapsed_string($ptime)
{
$etime = time() - $ptime;
if ($etime < 1)
{
return '0 seconds';
}
$a = array( 365 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
$a_plural = array( 'year' => 'years',
'month' => 'months',
'day' => 'days',
'hour' => 'hours',
'minute' => 'minutes',
'second' => 'seconds'
);
foreach ($a as $secs => $str)
{
$d = $etime / $secs;
if ($d >= 1)
{
$r = round($d);
return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
}
}
}
Run Code Online (Sandbox Code Playgroud)
称呼它
$update = $device->last_updated_utc_in_secs;
$ptime = date($update);
dd($this->time_elapsed_string($ptime)); //"0 seconds"
Run Code Online (Sandbox Code Playgroud)
我一直保持0秒。
您的问题在这里:
$etime = time() - $ptime;
Run Code Online (Sandbox Code Playgroud)
time()总是返回UNIX时间戳这是秒自Unix纪元过去(1970年1月1日00:00:00 GMT)。如果从中减去毫秒值(例如1448895141168),则总会得到负数(< 0)-因此您的第一个if条件会出现,并从方法中返回。只需将输入值除以1000(毫秒到秒),就可以了。