Home » Php » dateinterval – Add minutes to PHP Datetime to calculate start/end of event

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:

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'));

Answer:

If it is possible to change getStartTime() method’s return type, I highly recommend changing it from \DateTime to \DateTimeImmutable.

Then the code will go as follows:

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

More examples and advantages of this approach are described pretty well in this Nikola Poša’s blog article.