2017-02-08 141 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