Search code examples
phpleap-year

How to subtract a year from leap year


I'm looking for a solution for the following:

$date = new DateTime('02/29/2020');
$date->sub(new DataInterval('P1Y'));
$date->format('m/d/Y');

This Returns: 03/01/2019

Is there a way to return 02/28/2019? Thanks


Solution

  • date('L') returns true if a leap year, so:

    <?php
    
    $date = new DateTime('02/29/2020');
    $date->format('L') && $date->format('m-d') == '02-29' ? 'P366D' : 'P1Y';
    $date->sub(new DateInterval($interval));
    echo $date->format('m/d/Y');
    

    Check it out here https://3v4l.org/4mXX4