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

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

3 Comments

i don't need the date part.. i just need to add to times with this format H:m:s
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 ;))
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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.