I want to calculate total working hours of an employee for a month.The time for one session of an employee is stored in the format 'H:i:s' as as string in the database.How do I add these individual sessions to calculate total time.
Asked
Active
Viewed 164 times
0
-
Can't you convert it to seconds then sum it? – Chin Leung Apr 16 '19 at 15:57
-
You can't really. Without a date there's no way to know if the user went over midnight while working. That miscalculation might result in huge overpayments/underpayments. – user3783243 Apr 16 '19 at 16:02
-
share how exactly you are storing time ? share some example ? – Niklesh Raut Apr 16 '19 at 16:04
1 Answers
0
The function strtotime(datetime_today) will parse to seconds relative to the difference between the current datetime and 01/01/1970
<?php
$datetime_ref_today = '0:00:00';
$ar_times[]='00:00:10';
$ar_times[]='00:01:30';
$ar_times[]='13:50:30';
$total_time = 0;
foreach($ar_times as $val)
{
$total_time += strtotime($val)-strtotime($datetime_ref_today);
echo "<br/>cumul. total_time : ".$total_time." sec";;
}
echo "<br/><br/>total_time : ".$total_time." sec";
echo "<br/>Formated total_time (H:i:s): ".gmdate("H:i:s", $total_time);
?>

sylvain
- 853
- 1
- 7
- 20
-
-
While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. A ***good answer*** will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. – Jay Blanchard Apr 16 '19 at 16:11