Date minus 1 year?

前端 未结 8 1962
时光取名叫无心
时光取名叫无心 2020-11-27 14:28

I\'ve got a date in this format:

2009-01-01

How do I return the same date but 1 year earlier?

8条回答
  •  忘掉有多难
    2020-11-27 14:48

    Although there are many acceptable answers in response to this question, I don't see any examples of the sub method using the \Datetime object: https://www.php.net/manual/en/datetime.sub.php

    So, for reference, you can also use a \DateInterval to modify a \Datetime object:

    $date = new \DateTime('2009-01-01');
    $date->sub(new \DateInterval('P1Y'));
    
    echo $date->format('Y-m-d');
    

    Which returns:

    2008-01-01
    

    For more information about \DateInterval, refer to the documentation: https://www.php.net/manual/en/class.dateinterval.php

提交回复
热议问题