Loek Loek - 6 months ago 118
PHP Question

PHP DateTime first day of next year

I wonder if there is a 'correct' way to call:

$endDate = new DateTime('first day of next year');


I know the PHP parser expects a month after
of
(see here), but
next year
seems to work sort of as intended. If the month is May, it will state April 1st of next year as
$endDate
.

Ofcourse we can hack around this with:

$endDate = new DateTime('first day of january');
$endDate = $endDate->modify('+1 year');


But I can't imagine nobody would have fixed this 'bug' since PHP 5.3 came out 7 years ago.

Answer

It's not quite as unambiguous as you might be looking for (are there any situations where January isn't the first month?), but this works fine back to PHP 5.2

$endDate = new DateTime('1st January Next Year');
echo $endDate->format('Y-m-d'); // 2017-01-01

https://3v4l.org/H5P8s