1

I have a table to store machine start and stop records like that

 ---------------------------------------
|   machine_start   |   machine_stop    |
 ---------------------------------------
|       11:00 AM    |       11:00 PM    |
 ---------------------------------------
|       12:00 AM    |       01:00 PM    |
 ---------------------------------------

Now I want to get total machine operating time by first get the difference between machine_stop and machine_start time and loop through the table records to get the total time.

Here I have tried

$machine_total_time = 0;
foreach ($machine_data as $data){
    $machine_total_time += strtotime($data->machine_stop) - strtotime($data->machine_start);
}
var_dump(date("H:i", $machine_total_time));

It will show the highest 23 hours for 'H'. I want to show the total hours and minutes from $machine_total_time. How to do that. Thanks.

Ashis Biswas
  • 747
  • 11
  • 28
  • 1
    What happens if the machine starts at `11 AM` and stops at `4 PM` two days later? Without dates, you won't know how long it was running. – M. Eriksson Apr 11 '19 at 11:58
  • :) Good Question. From your point of view, you are right. But this is just an example so that I can understand the basic problem. – Ashis Biswas Apr 11 '19 at 12:01
  • @Joni he has to convert seconds to hours, what you've linked is not what op wants – Andrei Lupuleasa Apr 11 '19 at 12:04
  • Possible duplicate of https://stackoverflow.com/questions/3172332/convert-seconds-to-hourminutesecond This question has been asked and answered dozens if not hundreds of times on this site – Joni Apr 11 '19 at 12:14
  • Your code is fine all you need is to use one of the methods described in the duplicates to output your time. – Nick Apr 11 '19 at 12:15

2 Answers2

0

You can use the gmdate() function:

$minsec = gmdate("i:s", $machine_total_time); 
$hours = gmdate("d", $machine_total_time)*24 + gmdate("H", $machine_total_time);

$time = $hours . ':' . $minsec; // 56:12:12
Andrei Lupuleasa
  • 2,677
  • 3
  • 14
  • 32
0

Run this code, the total output should be 25 hours,

$machine_total_time = 0;
foreach ($machine_data as $data) {
    $time1    = new DateTime(date("H:i:s", strtotime($data['machine_stop'])));
    $time2    = new DateTime(date("H:i:s", strtotime($data['machine_start'])));
    $interval = $time1->diff($time2);
    $machine_total_time += $interval->h;
}
echo $machine_total_time;

interval documentation please refer to see options to fetch data from interval.

Rahul
  • 18,271
  • 7
  • 41
  • 60