I have a small issue while calculating sum of total hours
My working hours is like:
Day1 - 12:23 Hours
Day2 - 11:43 Hours
Day3 - 10:18 Hours
How can I get it by php? Thanks in advance
Just add them like this:
$day1hours = "12:23";
$day2hours = "11:43";
$day1 = explode(":", $day1hours);
$day2 = explode(":", $day2hours);
$totalmins = 0;
$totalmins += $day1[0] * 60;
$totalmins += $day1[1];
$totalmins += $day2[0] * 60;
$totalmins += $day2[1];
$hours = $totalmins / 60;
$minutes = $totalmins % 60;
$totalhours = "$hours.$minutes";
It is quite elaborate like this, but it just to show the idea: calculate back to minutes, add minutes together, then calculate back to hours.
Note that PHP has quite extensive support for dates and times. Consider using that: http://www.php.net/manual/en/book.datetime.php
If you use this function to calculate time calculation then it will work
function sumTime($initialHour, $finalHour) {
$h = date('H', strtotime($finalHour));
$m = date('i', strtotime($finalHour));
$s = date('s', strtotime($finalHour));
$tmp = $h." hour ".$m." min ".$s." second";
$sumHour = $initialHour." + ".$tmp;
$newTime = date('H:i:s', strtotime($sumHour));
return $newTime;
};
For more explanation refer this link: Time Calculation in php
This technique will give exact total hours and minutes. The above answer gives me 1.25.15 when i add 00:30 and 00:45
<?php
$hourMin = array("00:30","00:45"); //an Multiple Hour:Minutes array
$hours = 0;
$mins = 0;
foreach($hourMin as $val)
{
$explodeHoursMins = explode(':',$val);
$hours += $explodeHoursMins[0];
$mins += $explodeHoursMins[1];
}
$minToHours = date('H:i', mktime(0,$mins)); //Calculate Hours From Minutes
$explodeMinToHours = explode(':',$minToHours);
$hours += $explodeMinToHours[0];
$finalMinutes = $explodeMinToHours[1];
echo $hours." : ".$finalMinutes;
?>