Search code examples
phpdatedatetimesubtraction

PHP: why year not subtracted from date?


The below code doesn't subtract 1 year from the date. Why?

$date1 = '2021-06-02';
$date2 = new \DateTime(date($date1, strtotime('-1 year')));
echo $date2->format('Y-m-d'); // outputs the same date 2021-06-02

Solution

  • Please use this code. Its always works for me.

    $date1 = '2021-06-02';
    $date2 = date("Y-m-d", strtotime("-1 year", strtotime($date1)));
    echo $date2; //Output 2020-06-02
    

    This is for Date time object:

    $dt = new DateTime('2021-06-02');
    $minusOneYearDT = $dt->sub(new DateInterval('P1Y'));
    $minusOneYear = $minusOneYearDT->format('Y-m-d');    
    echo $minusOneYear;
    

    OR make a small solution:

    $time = new DateTime('2021-06-02');
    $newtime = $time->modify('-1 year')->format('Y-m-d');
    echo $newtime;