How to have a DateTime() object for next year?

I need a DateTime() object for next year. I did this:

new DateTime(date('Y-m-d', strtotime("+1 year")));

Does it make sense or any better practice?

DateTime’s constructor can take relative formats directly.
new DateTime("next year")

<?php
$date = new DateTime('next year');
echo $date->format('Y-m-d H:i:s');
?>

Output:
2020-10-09 21:11:51

1 Like

What about ‘next 2 year’? Is it something valid?

If you just tried you would have gotten your answer a lot faster :slight_smile:

You would have seen this:

PHP Fatal error:  Uncaught Exception: DateTime::__construct(): Failed to parse time string (next 2 year) at position 0

So no, it’s not possible.
What is possible is +2 year.

You can learn all about it here: https://www.php.net/manual/en/datetime.formats.relative.php

1 Like

If you want to try some PHP real quick you can use a website like http://sandbox.onlinephpfunctions.com/

There you can put some code and evaluate using different versions of PHP.

If you want to quickly check the behaviour of different PHP versions you can use https://3v4l.org/

Or if you just want to try something locally you can run from the command line, like I just did to get the answer for the post above, where I ran this:

php -r 'echo (new DateTime("next 2 year"))->format("Y-m-d H:i:s");'
3 Likes