需要弄清楚如何在PHP中倒计时

时间:2012-08-20 20:54:39

标签: php

我有时间戳并希望向我的用户显示...最后发送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 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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秒前

答案 2 :(得分: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

答案 3 :(得分:0)

你需要很多if'smodulus (%)floor()(不是round())

Google; - )