将毫秒时间戳转换为前一个时间戳

时间:2015-11-30 16:13:21

标签: php datetime unix timestamp

我有一个以毫秒为单位的时间戳

$update = 1448895141168

我正在努力将这段时间转换为人类可读时间(之前)。

示例, 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';
            }
        }
    }

调用

        $update = $device->last_updated_utc_in_secs;
        $ptime = date($update);
        dd($this->time_elapsed_string($ptime)); //"0 seconds"

我持续0秒。

1 个答案:

答案 0 :(得分:4)

你的问题在这里:

$etime = time() - $ptime;

time()始终返回UNIX时间戳,即自Unix Epoch(1970年1月1日00:00:00 GMT)以来经过的。如果您从中减去毫秒值(例如1448895141168),您将始终得到负值(< 0) - 因此您的第一个if条件会被解除in并从方法返回。只需将您的输入值除以1000(毫秒到秒),就可以了。