Home > Net >  How to get the timestamp X minutes with DateTime and DateInterval
How to get the timestamp X minutes with DateTime and DateInterval

Time:11-03

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:

$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.

CodePudding user response:

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');
  •  Tags:  
  • php
  • Related