Search code examples
php

Adding 12 months to February 29


I want to add 12 months to my date. My start date is 02/29/2020 and I want to add 12 months to this.

Code:

$startdate = '02/29/2020';
date('m/d/Y', strtotime('+12 months', strtotime($startdate)));

Output:

03/01/2021

I used this code to add 12 months but the output is 03/01/2021, when the real output should be 02/28/2020.


Solution

  • Have a look!

     function add_months($months, DateTime $dateObject) 
       {
            $next = new DateTime($dateObject->format('Y-m-d'));
            $next->modify('last day of +'.$months.' month');
    
            if($dateObject->format('d') > $next->format('d')) {
                return $dateObject->diff($next);
            } else {
                return new DateInterval('P'.$months.'M');
            }
        }
    
    function getCalculatedDate($d1, $months)
    {
        $date = new DateTime($d1);
    
        // call second function to add the months
        $newDate = $date->add(add_months($months, $date));
    
        //formats final date to m/d/Y form
        $dateReturned = $newDate->format('m/d/Y'); 
    
        return $dateReturned;
    }
    

    An example would be:-

    $startDate = '02/29/2020';
    $nMonths = 12; // choose how many months you want to add
    $finalDate = getCalculatedDate($startDate, $nMonths); // output: 02/28/2021
    

    This way you will get the output of 02/28/2021