skip to Main Content

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’

2

Answers


  1. Chosen as BEST ANSWER

    Here is the solution :

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

    Thanks to shingo


  2. if its a leap year subtract one day from origin

    $copy = new DateTime('2024-02-29');
    if(date('L', mktime(0, 0, 0, 1, 1, $copy->format('Y')))){
        $copy->modify("-1 day");
    }
    $lastDay = new DateTime($copy->add((new DateInterval('P1Y')))->format('Y-m-t'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search