How to add one year to a DateTime in a leap Year

86 Views Asked by At

I want to get the last day of the month of the next year from a given date

Here is how I did :

$copy = new \DateTime();
$lastDay = new \DateTime($copy->add((new \DateInterval('P1Y')))->format('Y-m-t'));

This works exept in this exemple :

$copy = new \DateTime('2024-02-29');
$lastDay = new \DateTime($copy->add((new \DateInterval('P1Y')))->format('Y-m-t'));

It returns me '2025-03-31' while I want '2025-02-28'

1

There are 1 best solutions below

1
Gautier On

Here is the solution :

$lastDay = $copy->modify('first day of next year last day of this month');

Thanks to shingo