0

我有一个时间戳,想向我的用户显示...上次发送时间是 1 天 23 小时 54 分 33 秒前。我知道如何获得时间差异...

$timePast = '2012-08-18 22:11:33';
$timeNow = date('Y-m-d H:i:s');
// gives total seconds difference
$timeDiff = strtotime($timeNow) - strtotime($timePast);

现在我被卡住了,无法像上面那样显示时间。x 天,x 小时,x 分钟,x 秒,其中所有 x 的总和应为总秒时差。我知道以下...

$lastSent['h'] = round($timeDiff / 3600);
$lastSent['m'] = round($timeDiff / 60);
$lastSent['s'] = $timeDiff;

需要你帮忙!提前致谢。

4

4 回答 4

1

不要手动做日期数学!

PHP 可以使用DateTimeDateInterval类为您计算出所有的日期/时间数学。

获取两个日期之间的间隔

$timePast = new DateTime('2012-08-18 22:11:33');
$timeNow  = new DateTime;

$lastSent = $timePast->diff($timeNow);
// $lastSent is a DateInterval with properties for the years, months, etc.

格式化示例

获取格式化字符串的函数可能如下所示(尽管这只是众多方法中的一种超级基本方法)。

function format_interval(DateInterval $interval) {
    $units = array('y' => 'years', 'm' => 'months', 'd' => 'days',
                   'h' => 'hours', 'i' => 'minutes', 's' => 'seconds');
    $parts = array();
    foreach ($units as $part => $label) {
        if ($interval->$part > 0) {
            $parts[] = $interval->$part . ' ' . $units[$part];
        }
    }
    return implode(', ', $parts);
}

echo format_interval($lastSent); // e.g. 2 days, 24 minutes, 46 seconds
于 2012-08-20T21:41:15.447 回答
1

我采用了 Kalpesh 的代码,并通过使用floor而不是round计算一天中的不同摩擦来使其工作。它是这样的:

function timeAgo ($oldTime, $newTime) {
    $timeCalc = strtotime($newTime) - strtotime($oldTime);
    $ans = "";
    if ($timeCalc > 60*60*24) {        
        $days = floor($timeCalc/60/60/24);
        $ans .=  "$days days"; 
        $timeCalc = $timeCalc - ($days * (60*60*24));        
    }
    if ($timeCalc > 60*60) {
        $hours = floor($timeCalc/60/60);
        $ans .=  ", $hours hours"; 
        $timeCalc = $timeCalc - ($hours * (60*60));        
    }
    if ($timeCalc > 60) {
        $minutes = floor($timeCalc/60);
        $ans .=  ", $minutes minutes"; 
        $timeCalc = $timeCalc - ($minutes * 60);        
    }    
    if ($timeCalc > 0) {
        $ans .= "and $timeCalc seconds";        
    }
    return $ans . " ago";
} 
$timePast = '2012-08-18 22:11:33';
$timeNow = date('Y-m-d H:i:s');    
$t = timeAgo($timePast, $timeNow);
echo $t;

输出
1 天 16 小时 11 分 18 秒前

于 2012-08-20T21:21:42.093 回答
1

在这之后:

$timeDiff = strtotime($timeNow) - strtotime($timePast);

添加:

if ($timeDiff > (60*60*24)) {$timeDiff = floor($timeDiff/60/60/24) . ' days ago';}
else if ($timeDiff > (60*60)) {$timeDiff = floor($timeDiff/60/60) . ' hours ago';}
else if ($timeDiff > 60) {$timeDiff = floor($timeDiff/60) . ' minutes ago';}
else if ($timeDiff > 0) {$timeDiff .= ' seconds ago';}

echo $timeDiff;
于 2012-08-20T20:58:42.487 回答
0

你需要很多if's模数 (%)floor()(不是 round())

谷歌;-)

于 2012-08-20T21:01:40.627 回答