Desquid Desquid - 6 months ago 13
PHP Question

Best way to create a dateTime object 30 minutes after another one?

So I have the following code to create a DateTime object based on another and it seems inefficient. I'm sure there's a way to simplify this to one line but I can't seem to find it.

$startTime = new DateTime('20:00');
$endTime = clone $startTime;
$endTime->add(new DateInterval('PT30M'));

Answer

You can simply use DateTimeImmutable to do it very easily:

$startTime = new DateTimeImmutable('20:00');
$endTime = $startTime->add(new DateInterval('PT30M'));

See: http://php.net/manual/en/class.datetimeimmutable.php

This class behaves the same as DateTime except it never modifies itself but returns a new object instead.

Comments