Add minutes to PHP Datetime to calculate start/end of event

Stefano picture Stefano · Dec 8, 2012 · Viewed 25.1k times · Source

I would like to calculate with PHP the start and end datetime of an event. I get the start of this event and the duration to add to get the end. So I tried the following code:

$startTime = $this->getStartTime();
$endTime = $this->getStartTime();

$endTime->add(new DateInterval('PT75M'));

in this example I add 75 minutes to the start time and I calculate the end of the event. It works, however it edits also the start time. I read in the PHP docs that the ADD method edits the object which is called on but I don't understand how it could edit the startEdit variable. I don't use reference in any of the methods that I wrote in the example, neither in the getStartTime function

Answer

Benjamin Paap picture Benjamin Paap · Dec 8, 2012

You have to create a new DateTime instance for that or you will be editing your original reference to your start date DateTime object. Try something like this:

$endTime = clone $startTime;
$endTime->add(new DateInterval('PT75M'));