当前时间与先前节省的时间之间的时间差计算

时间:2014-09-11 13:58:07

标签: php time

说明 我编写了以下函数来计算两次之间的差异。它有时会显示一个非常有趣和奇怪的计算...有时候它工作得很完美..这段代码有什么问题?

PHP

function get_the_time_of_post($datetime1,$datetime2)
{
$month =  date("F",strtotime($datetime1));
$day = date("d",strtotime($datetime1));
$a = new DateTime($datetime1);
$b = new DateTime($datetime2);
$interval = $a->diff($b);

$hours = $interval->format("%H");
$seconds = $interval->format("%S");
$days = $interval->format("%D");
$minutes = $interval->format("%I");

$date_statement_return = $month." , ".$day;
if($days == 0)
{
    if($hours == 0)
    {
        if($minutes == 0)
        {
            if($seconds >= 0 && $seconds <=30)
            {

                $date_statement_return = $date_statement_return." <span style = 'font-size: 12px;'> moment ago</span>";
            }
            else 
            {
                $date_statement_return = $date_statement_return."<span style = 'font-size: 12px;'> ".$seconds." secs ago </span>";
            }
        }

        else if ($minutes >= 1 && $minutes <= 59)
        {
            $date_statement_return = $date_statement_return."<span style = 'font-size: 12px;'> ".$minutes." mins ago </span>";
        }
    }

    else if ($hours >= 1 && $hours <24)
    {
        $date_statement_return = $date_statement_return."<span style = 'font-size: 12px;'> ".$hours." hrs ago </span>";
    }

}

else if ($days > 0 && $days < 3)
{
    if($days == 1)
    {
        $date_statement_return = $date_statement_return."<span style = 'font-size: 12px;'> yesterday </span>";
    }
    else
    {
        $date_statement_return = $date_statement_return."<span style = 'font-size: 12px;'> ".$days." days ago </span>";
    }
}
return $date_statement_return;
}

1 个答案:

答案 0 :(得分:1)

您正在使用返回带前导零的值的格式字符。这使得与其他数字的比较变得尴尬并且容易出错。

$hours   = $interval->format("%h");
$seconds = $interval->format("%s");
$days    = $interval->format("%d");
$minutes = $interval->format("%i");