Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the timestamp + X minutes with DateTime and DateInterval

I want to get the timestamp in 15 minutes from now.

I don’t want to use strtotime, I want to use DateTime and DateInterval.

I’m doing:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$now = new DateTime('now');
$in_15_m = $now->add(new DateInterval('PT15M'));

echo 'Now:' . $now->format('Y-m-d\TH:i:s\Z');
echo 'In 15 min': . $in_15_m->format('Y-m-d\TH:i:s\Z');

But both printed lines contain the same date.

How can I achieve this?

The arguments for DateInterval aren’t really clear in the docs, though I think I am using it the correct way.

Thanks.

>Solution :

The DateTime::add method modifies the DateTime object in place. It also returns the modified object for use in method chaining, but the original object is still modified.

You can use DateTimeImmutable instead:

$now = new DateTimeImmutable('now');
$in_15_m = $now->add(new DateInterval('PT15M'));
echo 'Now:' . $now->format('Y-m-d\TH:i:s\Z');
echo "\n+15m:" . $in_15_m->format('Y-m-d\TH:i:s\Z');

Or, alternatively, use two objects:

$now = new DateTime('now');
$in_15_m = (new DateTime('now'))->add(new DateInterval('PT15M'));
echo 'Now:' . $now->format('Y-m-d\TH:i:s\Z');
echo "\n+15m:" . $in_15_m->format('Y-m-d\TH:i:s\Z');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading