如何让PHP总时间?

问题描述:

我在PHP中创建了工作总时间程序 - 给出输入时间 - 1.30,2.10,1.40并获得输出时间 - 4.80(8小时)。但我需要输出时间 - 5.20(8.40小时)。 备注:1.30 + 2.10 + 1.40 = 4.80(8小时),但我需要5.20(8.40小时)。请帮我...如何让PHP总时间?

+0

只需添加额外的40分钟即可。或者有什么你不告诉我们的? – dave4420 2009-12-16 13:09:53

+1

4.80 = 8小时和5.20 = 8.40小时?什么样的时间测量是?爱因斯坦相对论什么的? – Lukman 2009-12-16 13:09:53

+0

4.80和8小时一样,我错过了什么? – 2009-12-16 13:10:02

1.30 + 2.10 + 1.40是错误的。应该是:

((1 * 60)+ 30)+((2 * 60)+ 10)+((1 * 60)+ 40)= 320(分钟)

320分钟=5小时和20分钟。

你需要跟踪分钟和秒的分别:

$minutes = array(); 
$seconds = array(); 
foreach ($times as $time) { 
    $parts = explode('.', $time); 
    $minutes[] = $time[0]; 
    $seconds[] = $time[1]; 
} 
$total_minutes = array_sum($minutes); 
$total_seconds = array_sum($seconds); 
while ($total_seconds > 60) { 
    $total_minutes++; 
    $total_seconds -= 60; 
} 
echo $total_minutes . ' minutes and ' . $total_seconds . ' seconds'; 

从PHP网站摘录为您的乐趣:

function AddTime ($oldTime, $TimeToAdd) { 
    $pieces = split(':', $oldTime); 
    $hours=$pieces[0]; 
    $hours=str_replace("00","12",$hours); 
    $minutes=$pieces[1]; 
    $seconds=$pieces[2]; 
    $oldTime=$hours.":".$minutes.":".$seconds; 

    $pieces = split(':', $TimeToAdd); 
    $hours=$pieces[0]; 
    $hours=str_replace("00","12",$hours); 
    $minutes=$pieces[1]; 
    $seconds=$pieces[2]; 

    $str = $minutes." minute ".$seconds." second" ; 
    $str = "01/01/2000 ".$oldTime." am + ".$hours." hour ".$minutes." minute ".$seconds." second" ; 

    if (($timestamp = strtotime($str)) === false) { 
    return false; 
    } else { 
    $sum = date('h:i:s', $timestamp); 
    $pieces = split(':', $sum); 
    $hours = $pieces[0]; 
    $hours = str_replace("12", "00", $hours); 
    $minutes = $pieces[1]; 
    $seconds = $pieces[2]; 
    $sum = $hours.":".$minutes.":".$seconds; 
    return $sum; 
    } 
} 

$firstTime = "00:03:12"; 
$secondTime = "02:04:34"; 

$sum=AddTime($firstTime, $secondTime); 

if($sum != false) { 
    echo $firstTime." + ".$secondTime." = ".$sum; 
} else { 
    echo "failed"; 
} 

输出:

00:03:12 + 02:04:34 = 02:07:46 
+0

这段代码具有良好的开销IMO,但会为你工作。 – 2009-12-16 13:31:56

对于每个编号(代表下面的$t)你可以这样做:

// start with $total=0 
$hours = floor($t); // 1.10 -> 1 hr 
$minutes = ($t - $hours) * 100; // 1.10 -> 10 mins 
$total += ($hours * 60) + $minutes; 

这会给你总分钟数。要分别获得小时/分钟,请执行以下操作:

$total_mins = $total % 60; // 130 -> 10 mins 
$total_hours = ($total - $total_mins)/60; // 130 -> 2 hrs