0

I'm totalling up time like so.

$totalTimeDiff = new DateTime("@0");
foreach($dbrecords as $row)
{
    $timeDiff = date_diff( ... two datetimes from my database ... )
    $totalTimeDiff->add($timeDiff);
}

So $totalTimeDiff is a DateTime object with the sum of all of the time differences added together (so a sum of all of the durations). How can I get the total time in seconds?

muttley91
  • 12,278
  • 33
  • 106
  • 160
  • 1. use `DateInterval`, as you are calculating a proper interval and not storing a date; 2. read its documentation in order to get your interval in seconds. – moonwave99 Jan 29 '14 at 02:04
  • If I use date_diff to get a difference, how can I convert that to seconds? I didn't see that in the documentation. I just see how to retrieve the seconds from there. – muttley91 Jan 29 '14 at 02:24
  • [Just compute the difference with _now_](http://stackoverflow.com/questions/3176609/calculate-total-seconds-in-php-dateinterval). – moonwave99 Jan 29 '14 at 10:40

4 Answers4

0

Why not keep it simple?

$totalseconds=0;
foreach($dbrecords as $row)
  $totalseconds+=(UNIX_TIMESTAMP(second_datetime)-UNIX_TIMESTAMP(first_datetime));
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
0

use strtotime function

echo strtotime('01:00:00') - strtotime('TODAY');

Shinto Joseph
  • 1,081
  • 8
  • 8
0
$totalTimeDiff->format('U');
evalarezo
  • 1,134
  • 7
  • 13
0

Taking moonwave99's advice, I used DateInterval (can't remember why I went with DateTime for that in the first place, possibly a workaround for something at another stage of the project) and computed the seconds by adding each value to the total after converting it to seconds (converting hours and minutes to seconds and summing them up). I did this by using the DateInterval class's seconds property as well as the following function to convert a DateInterval to seconds (Note: only accounted for days, hours, minutes, and seconds for my specific case as there's no chance the amount will exceed one month):

function convertDateIntervalToSeconds($dateInterval)
{
    $days = $dateInterval->d * 24 * 60 * 60;
    $hours = $dateInterval->h * 60 * 60;
    $minutes = $dateInterval->i * 60;
    $seconds = $dateInterval->s;

    return $hours + $minutes + $seconds;
}
muttley91
  • 12,278
  • 33
  • 106
  • 160