2016-06-18 71 views
0

我有1臺「INUSE」 INUSE:2列:START_TIME,END_TIME比較時,並顯示在時間格式最短的時間

我要計算每個START_TIME & END_TIME之間的差異,差異應該是最小和差異我想顯示在PHP頁面。

我的代碼被賦予

<?php 
    $link= mysqli_connect("localhost", "cl52-mayur", "N-wtsV/Re", "cl52-mayur"); 

    if($link) 
    { 
    echo"success"; 
    } 
    $query = "SELECT start_time, end_time FROM `inuse` ORDER BY u_id ASC LIMIT 0 , 30 "; 

if($result = mysqli_query($link, $query) or die(mysqli_error())) 
    { 
    $min=999999; 

    while($fieldinfo = mysqli_fetch_array($result) or die(mysqli_error())) 
    { 
     $st=$fieldinfo['start_time']; 
     $et=$fieldinfo['end_time']; 

     $s_time = new DateTime($st); 
     $e_time = new DateTime($et); 

    //$sdate = $s_time->format('Y-m-d'); 
     $stime = $s_time->format('H:i:s'); 

    //$edate = $e_time->format('Y-m-d'); 
    $etime = $e_time->format('H:i:s'); 

    $comp1= str_replace(':', '', $stime); 
    $comp2 = str_replace(':', '', $etime); 

    for($i=1;$i<2;$i++) 
     { 
      if($time<$min) 
      { 

       $min=$time; 
      } 
     } 

     echo date("H:i:s", $min); 
    } 

    } 
    else { 
      $error = "Error...Please try again."; 
     } 

    ?> 

是表示我的區別,但我想表明,在時間格式。 請提前幫忙,謝謝。

+1

'MIN'和'TIMEDIFF' mysql函數 –

回答

0

終於來到了解決方案。 答案:

<?php 
    function time_to_decimal($time) { 
    $timeArr = explode(':', $time); 
    $decTime = ($timeArr[0]*60) + ($timeArr[1]) + ($timeArr[2]/60); 

    return $decTime; 
    } 

    function decimal_to_time($decimal) { 
     $hours = floor((int)$decimal/60); 
     $minutes = floor((int)$decimal % 60); 
     $seconds = $decimal - (int)$decimal; 
     $seconds = round($seconds * 60); 

    return str_pad($hours, 2, "0", STR_PAD_LEFT) . ":" . str_pad($minutes, 2, "0", STR_PAD_LEFT) . ":" . str_pad($seconds, 2, "0", STR_PAD_LEFT); 
    } 


    $link= mysqli_connect("localhost", "cl52-mayur", "N-wtsV/Re", "cl52-mayur"); 

if($link) 
    { 
    echo"success"; 
    } 
    $query = "SELECT start_time, end_time FROM `inuse` ORDER BY u_id ASC LIMIT 0 , 30 "; 

$min=999999; 

$result = mysqli_query($link, $query) or die(mysqli_error()); 

     while($fieldinfo = mysqli_fetch_array($result)) 
     { 

      $st=$fieldinfo['start_time']; 
      $et=$fieldinfo['end_time']; 

      $s_time = new DateTime($st); 
      $e_time = new DateTime($et); 

      $stime = $s_time->format('H:i:s'); 
      $etime = $e_time->format('H:i:s'); 

     //function call 

     $stime= time_to_decimal($stime); 
     $etime= time_to_decimal($etime); 


     $time=$etime-$stime; 

      if($time<$min) 
      { 

       $min=$time; 
      } 
     } 

    $min=decimal_to_time($min); 

    ?>