2013-07-16 66 views
0

具有以下值:PHP計算產生負數?

$a[0] = "4:00:00 am" 
$b[0] = "8:00:00 am" 
$c[0] = "9:00:00 am" 
$d[0] = "1:22:00 pm" 

爲什麼會如果在一個-8值語句結果被寫入到數據庫中的第二個?第一條if語句導致適當的4小時值,但不是第二條。是因爲上午/下午的變化還是什麼?

if (!$a[0]=="" AND !$b[0]=="") { 
    $start = explode(':', $a[0]); 
    $end = explode(':', $b[0]); 
    $total_hours = $end[0] - $start[0] - ($end[1] < $start[1]); 
    mysqli_query($con,"UPDATE timeclock SET daily_hours='$total_hours' WHERE idex='$data[idex]' AND date='$date' AND status='slunch'"); 
} 

if (!$c[0]=="" AND !$d[0]=="") { 
    $start = explode(':', $c[0]); 
    $end = explode(':', $d[0]); 
    $total_hours = $end[0] - $start[0] - ($end[1] < $start[1]); 
    mysqli_query($con,"UPDATE timeclock SET daily_hours='$total_hours' WHERE idex='$data[idex]' AND date='$date' AND status='ework'"); 
} 

回答

1

因爲1:00 - 上午09點是1 - 9等效,這是-8。您需要將您的下午時間轉換爲24小時制,例如

1pm -> 13 
9am -> 9 

13 - 9 = 4 
+0

得到它,應該抓住這一點。謝謝 – DMSJax

0

您的代碼正如其應該的那樣工作。這只是您將時間減去而不將其轉換爲24小時格式。

您可以使用date()做轉換,比如:

$time_in_24 = date("H:i", strtotime("1:22:00 pm")); // 13:22 

你的代碼更改爲:

$a[0] = date("H:i", strtotime("4:00:00 am")); 
$b[0] = date("H:i", strtotime("8:00:00 am")); 
$c[0] = date("H:i", strtotime("9:00:00 am")); 
$d[0] = date("H:i", strtotime("1:22:00 pm")); 

,這應該修復它。

鍵盤:http://codepad.org/jsltDXK0

0
$a[0] = "4:00:00 am"; 
$b[0] = "8:00:00 am"; 
$c[0] = "9:00:00 am"; 
$d[0] = "1:22:00 pm"; 
if (!$a[0]=="" AND !$b[0]=="") { 
    $start = convert($a[0]); 
    $end = conver($b[0]); 
    $total_hours = $end[0] - $start[0] - ($end[1] < $start[1]); 
    mysqli_query($con,"UPDATE timeclock SET daily_hours='$total_hours' WHERE idex='$data[idex]' AND date='$date' AND status='slunch'"); 
} 

if (!$c[0]=="" AND !$d[0]=="") { 
    $start = convert($c[0]); 
    $end = convert($d[0]); 
    $total_hours = $end[0] - $start[0] - ($end[1] < $start[1]); 
    mysqli_query($con,"UPDATE timeclock SET daily_hours='$total_hours' WHERE idex='$data[idex]' AND date='$date' AND status='ework'"); 
} 

function convert($hour){ 
    $m = strtolower(substr($hour, -2));//am or pm 
    $hr = array_slice(explode(':', $hour), 0, 2); 
    if ($m == 'pm') $hr[0] += 12; 
    return $hr; 
}