时间不同无法正常工作?

时间:2017-02-08 05:40:41

标签: php

我试图在php中的两个时间表之间获得时间差,但它无法正常工作。

$stime="10:00 pm";
$sptime="11:30 pm";
//convert into 24hr format
$Cstime  = date("H:i:s", strtotime($stime));
$Csptime  = date("H:i:s", strtotime($sptime));

//call the method
$diff=get_time_different($Cstime,$Csptime);

//define method
function get_time_different($Cstime,$Csptime)
{
    $Cstime = strtotime("1/1/1980 $Cstime");
    $Csptime = strtotime("1/1/1980 $Csptime");

    if($Csptime<$Cstime)
    {
        $Csptime = $Csptime+ 86400;
    }

    return($Csptime-$Cstime) / 3600;
}
echo $diff;

输出

1.5

但我需要1.30。有什么问题

2 个答案:

答案 0 :(得分:1)

试试这个:

$stime="10:00 pm";
$sptime="11:30 pm"; 
$time1 = new DateTime(date('H:i:s',strtotime($stime)));
$time2 = new DateTime(date('H:i:s',strtotime($sptime)));
$diff = $time1->diff($time2);
echo $diff->h.'.'.$diff->i;

输出:

1.30

现在,你可以看到变量&#39; $ diff&#39;是一个对象,你可以看到小时,分钟,秒......

 public 'y' => int 0
 public 'm' => int 0
 public 'd' => int 0
 public 'h' => int 1
 public 'i' => int 30
 public 's' => int 0
 public 'weekday' => int 0
 public 'weekday_behavior' => int 0
 public 'first_last_day_of' => int 0
 public 'invert' => int 0
 public 'days' => int 0
 public 'special_type' => int 0
 public 'special_amount' => int 0
 public 'have_weekday_relative' => int 0
 public 'have_special_relative' => int 0

答案 1 :(得分:0)

尝试使用此代码将小时格式转换为

//$diff = 1.5;

$min = $diff*60;
$time = gmdate("H:i", ($min * 60));
echo $time; // output : 01:30