how get php total time?
i have created work total time program in PHP - give input time - 1.30, 2.10, 1.40 and get output time - 4.80(8 hrs). but i need output time - 5.20(8.40 hrs). Notes: 1.30+2.10+1.40=4.80(8 hrs), but i need开发者_JAVA百科 5.20(8.40 hrs). please help me...
1.30 + 2.10 + 1.40 is wrong. Should be:
((1 * 60) + 30) + ((2 * 60) + 10) + ((1 * 60) + 40) = 320 (minutes)
320 minutes = 5 hours and 20 minutes.
You need to keep track of minutes and seconds separately:
$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';
Excerpt from PHP site for your pleasure:
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";
}
Output:
00:03:12 + 02:04:34 = 02:07:46
For each number (represented as $t
below) you can do this:
// start with $total=0
$hours = floor($t); // 1.10 -> 1 hr
$minutes = ($t - $hours) * 100; // 1.10 -> 10 mins
$total += ($hours * 60) + $minutes;
That gives you the total number of minutes. To get hours/mins separately, do this:
$total_mins = $total % 60; // 130 -> 10 mins
$total_hours = ($total - $total_mins) / 60; // 130 -> 2 hrs
精彩评论