2017-02-08 94 views
1

我试图获得两个时间表在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

这是正确的1.5小时= 90分钟。这是0.5小时的30分钟。 – mishanon

+0

'返回($ Csptime- $ Cstime)/ 60;'以分钟为单位获得差异,它将返回90分钟。你的代码是正确的。 .5意味着一半的时间。 –

+0

谢谢你,我知道了 –

回答

0

试试这个代码小时转换为时间格式,

//$diff = 1.5; 

$min = $diff*60; 
$time = gmdate("H:i", ($min * 60)); 
echo $time; // output : 01:30 
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 

现在,你可以看到变量'$ diff'是一个对象,并且您可以使用小时,分钟,秒钟。

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