0

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.

Álvaro Franz
  • 699
  • 9
  • 26
  • 1
    Note you don't need DateInterval, as DateTime (like strtotime()) takes relative phrases as an argument, so you can just do something like `new DateTime('+15 minutes');` – Alex Howansky Nov 02 '22 at 15:39
  • 1
    [The docs for `DateTime::add`](https://www.php.net/manual/en/datetime.add.php) have the important part - the method *modifies* the object, rather than just returning an updated copy. So `$now` and `$in_15_m` end up with the same values. [This question about DateTimeImmutable](https://stackoverflow.com/questions/67536245/datetimeimmutable-vs-datetime) might be useful. – iainn Nov 02 '22 at 15:40
  • @iainn Thanks for your help, I was focusing too much on one thing and boom, doing it wrong where I was thinking to be right. – Álvaro Franz Nov 02 '22 at 15:46
  • 1
    Note that the default timezone for a DateTime is not necessarily UTC and that assumption, plus the hardcoding of `Z` as the timezone in the output, is a recipe for trouble down the line. Use `$now = new DateTime('now', new DateTimezone('UTC'));` or `$now->setTimezone(new DateTimezone('UTC'))`. – Sammitch Nov 02 '22 at 20:24
  • @Sammitch - Hey, appreciate that insight. I am working on this within some specific given circumstances. That's why it is that weird. This is very useful information. Thanks. – Álvaro Franz Nov 04 '22 at 08:55

1 Answers1

2

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');
David
  • 208,112
  • 36
  • 198
  • 279