1

I have two times in my database:

$time1 = "02:00:03";
$time2 = "04:00:04";

and I want to make add them $time1 + $time2 what is the best way to do that?

I have no problem with the diference cause I can do something like this:

$end = new DateTime($this->hora_final);
$start = new DateTime($this->hora_inicio);
$diff = $end->diff($start);

$diff->format('%H:%I:%S');

and it works perfectly... but i can't seem to find a way to add them... any ideas?

Regards

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
richardalberto
  • 515
  • 2
  • 9
  • 23

1 Answers1

1

DateTime::add(). It really doesn't make much sense to add two dates, thus you cannot treat $time2 as DateTime, to add it to time1. Usually you would say something like 01.04. + 2 days, but not 01.04. + 02.00. The method accepts an object of type DateInterval. To create it I suggest to use something like

list($hour, $min, $second) = explode(':', $time2);
$interval = new DateInterval("PT{$hour}H{$min}M{$second}S");

Now you should be able to add the interval to the date

$x = new DateTime($time1);
$y = $x->add($interval);

(untested)

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
  • i don't need the date part.. i just need to add to times with this format H:m:s – richardalberto Jul 07 '11 at 10:58
  • ehm ... thats what I described :? Its just about: `date + interval = date` and (according your "diff" example) `date - date = interval` (Matematical: `x - y = z <=> x = z + y` ;)) – KingCrunch Jul 07 '11 at 11:00
  • yep i haven't seen the modification when i posted the comment :) worked like a charm with a minor modification to: list($hour, $min, $second) = $time2; for list($hour, $min, $second) = explode(":", $time2); – richardalberto Jul 07 '11 at 11:07