PHP计算剩余时间

时间:2011-07-13 01:57:22

标签: php mysql

我有一个功能

function getEndTimeRemaining($timestamp, $format) {       
    $difference = $timestamp - time();
    if($difference < 0)
        return false;
    else{

        $min_only = intval(floor($difference / 60));
        $hour_only = intval(floor($difference / 3600));

        $days = intval(floor($difference / 86400));
        $difference = $difference % 86400;
        $hours = intval(floor($difference / 3600));
        $difference = $difference % 3600;
        $minutes = intval(floor($difference / 60));
        if($minutes == 60){
            $hours = $hours+1;
            $minutes = 0;
        }

        if($days == 0){
            $format = str_replace('Days', '?', $format);
            $format = str_replace('Ds', '?', $format);
            $format = str_replace('%d', '', $format);
        }
        if($hours == 0){
            $format = str_replace('Hours', '?', $format);
            $format = str_replace('Hs', '?', $format);
            $format = str_replace('%h', '', $format);
        }
        if($minutes == 0){
            $format = str_replace('Minutes', '?', $format);
            $format = str_replace('Mins', '?', $format);
            $format = str_replace('Ms', '?', $format);       
            $format = str_replace('%m', '', $format);
        }

        $format = str_replace('?,', '', $format);
        $format = str_replace('?:', '', $format);
        $format = str_replace('?', '', $format);

        $timeLeft = str_replace('%d', number_format($days), $format);       
        $timeLeft = str_replace('%ho', number_format($hour_only), $timeLeft);
        $timeLeft = str_replace('%mo', number_format($min_only), $timeLeft);
        $timeLeft = str_replace('%h', number_format($hours), $timeLeft);
        $timeLeft = str_replace('%m', number_format($minutes), $timeLeft);

        if($days == 1){
            $timeLeft = str_replace('Days', 'Day', $timeLeft);
            $timeLeft = str_replace('Ds', 'D', $timeLeft);
        }
        if($hours == 1 || $hour_only == 1){
            $timeLeft = str_replace('Hours', 'Hour', $timeLeft);
            $timeLeft = str_replace('Hs', 'H', $timeLeft);
        }
        if($minutes == 1 || $min_only == 1){
            $timeLeft = str_replace('Minutes', 'Minute', $timeLeft);
            $timeLeft = str_replace('Mins', 'Min', $timeLeft);
            $timeLeft = str_replace('Ms', 'M', $timeLeft);           
        }

      return $timeLeft;
    }
}

我传入MySQL datetime字段,转换为strtotime

getEndTimeRemaining(strtotime($get_auction_details_result['end_date']), "%mo").

它将返回分钟,如果剩下1分钟则返回1,如果只剩下几秒则返回0但是我想知道剩余的秒数,即剩余的24秒等。

由于

1 个答案:

答案 0 :(得分:3)

如果您使用的是PHP&gt; = 5.3

,则无需重新发明轮子

使用DateTime::diff()。返回的DateInterval为您提供了所需的所有部分,并且拥有自己的方法。