Yekver
Yekver

Reputation: 5185

Summing time in DateTime() objects

I have an array of DateTime() objects in which I store some time duration (like "H:i") How can I sum all elements in this array to get total time duration?

And it's also should be taken into account, that if total time duration is grater that 23:59, I have to be able to get nubmer of days.

is this possible?

I was trying to do like this:

$duration = new DateTime('00:00');

foreach($routes as $route) {
   $arrival_time = new DateTime();
   $arrival_time->setTimestamp($route->arrival_time);

   $departure_time = new DateTime();
   $departure_time->setTimestamp($route->departure_time);

   $leg_duration = $arrival_time->diff($departure_time);
   $duration->add($leg_duration);
}

but in $duration I got wrong time.

P.S.

Using $duration->add($leg_duration); I got subtracted from "24:00" time, why? For example if $leg_duration = new DateTime('02:10'); the result will be "21:50".

$duration->sub($leg_duration); add time to "24:00"

Is this right?

Upvotes: 0

Views: 235

Answers (2)

Elyor
Elyor

Reputation: 5532

echo sum_the_time('01:45:22', '17:27:03');

this will give you a result:

19:12:2

function sum_the_time($time1, $time2) {
  $times = array($time1, $time2);
  $seconds = 0;
  foreach ($times as $time)
  {
    list($hour,$minute,$second) = explode(':', $time);
    $seconds += $hour*3600;
    $seconds += $minute*60;
    $seconds += $second;
  }
  $hours = floor($seconds/3600);
  $seconds -= $hours*3600;
  $minutes  = floor($seconds/60);
  $seconds -= $minutes*60;
  // return "{$hours}:{$minutes}:{$seconds}";
  return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds); // Thanks to Patrick
}

I found from here

Upvotes: 0

Ale
Ale

Reputation: 1819

Concerning part of the question: you're using the diff() method in the inverted way, the code should actually be:

$leg_duration = $departure_time->diff($arrival_time);

Because in your code you are calculating $departure_time - $arrival_time (which is negative, thus giving you this "inverted" result).

Concerning the addition of time intervals, as a DateTime object contains a date too, you might have to do something like this to get a meaningful result:

$start = new DateTime('00:00');
$duration = $start;

// ...  your loop ...

$total = $start->diff($duration);

$total will be a DateInterval object, whose fields should contain your total time difference (although I didn't test this).

Upvotes: 1

Related Questions