-1

I have to find the total working time of a staff.

Variables in my hand is,

$work_time_start = "8:00:00";
$work_time_end = "18:00:00";
$lunch_break_start = "13:00:00";
$lunch_break_end = "14:00:00";

From this I have to find the total working time of a staff.

For example.

//example 1    

$work_start_time = "14:00:00";
$work_end_time = "14:25:00";

//The output should be: 00:25:00

//example 2

$work_start_time = "14:00:00";
$work_end_time = "10:25:00";

//The output should be: 06:25:00

How to achieve the required output. I have no idea.

Jithin Varghese
  • 2,018
  • 3
  • 29
  • 56
  • convert everything to plain seconds, then work with it and convert back for display as necesary. – Calimero Oct 24 '17 at 10:08
  • This is basically getting the time difference with some special cases. It's not an exact duplicate but you should be able to work out an answer based on the many many other similar questions out there. At least show us what you tried. – apokryfos Oct 24 '17 at 10:15
  • Why should output of example 2 be 06:25:00? Are you working in a mixture of 24 and 12 hour time formats without defining which is which? Don't expect any answer here to work if that's the case. You need to normalize your data. It's impossible to work with – IsThisJavascript Oct 24 '17 at 10:21

3 Answers3

1

Detailed answer as requested.

$work_time_start = "8:00:00";
$work_time_end = "18:00:00";
$lunch_break_start = "13:00:00";
$lunch_break_end = "14:00:00";

$worktime = convert_to_seconds($work_time_end) - convert_to_seconds($work_time_start);

$lunchtime = convert_to_seconds($lunch_break_end) - convert_to_seconds($lunch_break_start);

$worktime = $worktime - $lunchtime;
echo $worktime;


function convert_to_seconds($str_time)
{

    $str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);

    sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);

    $time_seconds = $hours * 3600 + $minutes * 60 + $seconds;

    return $time_seconds;
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
Umashankar Das
  • 601
  • 4
  • 12
-1

Hope this helps

$work_start_time =new DateTime("14:00:00");
$work_end_time = new DateTime("14:25:00");
$interval = $work_end_time->diff($work_start_time);

echo $interval->format('%H:%I:%S');
Rajan Benipuri
  • 1,772
  • 1
  • 9
  • 21
-1

Use the following code:

$work_time_start = "8:00:00";
$work_time_end = "18:00:00";
$lunch_break_start = "13:00:00";
$lunch_break_end = "14:00:00";
$total_time = strtotime($lunch_break_start) - strtotime($work_time_start) + strtotime($work_time_end) - strtotime($lunch_break_end);
echo date("h:i:s", mktime(0,0, round($total_time) % (24*3600)));
M. Paul
  • 361
  • 5
  • 18