3

start time and end time in a database table using php and I am calculating the difference between the start time and end time to get the total duration total of a task.

I am using the following method:

 foreach ($task->timers as $time ) {
    $start_date = new DateTime($time->date.' '.$time->start_time);
    $end_date = new DateTime($time->date.' '.$time->end_time);
    $times[] = date_diff($end_date, $start_date);
   }

I then loop through the array above as follows;

  foreach ($times as $timer) {
        $minutes = strlen($timer->i);
        if($minutes == 1) {
            $minutes = '0'.$timer->i;
        } else {
            $minutes = $timer->i;
        }
        $o[] = $timer->h.':'.$minutes.':'.$timer->s;
    }

I then get an array as follows;

array(2) { [0]=> string(7) "0:54:17" [1]=> string(7) "0:01:26" }

Now I want to add those two values together to get the total duration and I'm attempting to do this as follows;

    $totalTime = array_sum($o);

however this comes back as :

int(0);

Any ideas how I can calculate the total duration of two durations??

user0129e021939232
  • 6,205
  • 24
  • 87
  • 140
  • I'm not sure if this is the correct approach. You may have to explicitly convert the values back to seconds before adding. Something like this: http://stackoverflow.com/questions/5718361/confusion-with-adding-2-time-values – Maximus2012 Nov 20 '15 at 23:02
  • 1
    What database are you using, can you not calculate the difference in the database query? – llanato Nov 20 '15 at 23:04
  • While you are building the first array you could get the start and end times in seconds and calculate the time differences at the same time in seconds as per Maximus' comment and add them together at that point. Then use Rajdeep Paul's floor(... code to turn the whole lot into h:m:s See http://stackoverflow.com/questions/4834202/convert-hhmmss-to-seconds-only for a conversion method – Steve Nov 20 '15 at 23:28

1 Answers1

2

Unfortunately array_sum does not work on strings, only on numerical values (because PHP has no clue how to do math with strings obviously). You could simply add up like this:

$hrs = 0;
$mins = 0;
$secs = 0;

foreach ($o as $time) {
    // Let's take the string apart into separate hours, minutes and seconds
    list($hours, $minutes, $seconds) = explode(':', $time);

    $hrs += (int) $hours;
    $mins += (int) $minutes;
    $secs += (int) $seconds;

    // Convert each 60 minutes to an hour
    if ($mins >= 60) {
        $hrs++;
        $mins -= 60;
    }

    // Convert each 60 seconds to a minute
    if ($secs >= 60) {
        $mins++;
        $secs -= 60;
    }
}

Now you will have $mins with a value of 55 and $secs with a value of 43. You can print them in any desired format again, like:

echo sprintf('%d:%d:%d', $hrs, $mins, $secs);

Which would result in 0:55:43.

Oldskool
  • 34,211
  • 7
  • 53
  • 66