last year, this year, next year with php DateTime

Viewed 6035

I am trying to create a dropbox that will display the last year, the current year and the next year using the php DateTime object.

In my current code I create three objects and have to call a method on 2 of them. This seems a bit heavy on the resources.

$today = new DateTime();
$last_year=new DateTime();
$last_year->sub(new DateInterval('P1Y'));
$next_year = new DateTime();
$next_year->add(new DateInterval('P1Y'));
echo date_format($last_year, 'Y').' '.date_format($today, 'Y').' '.date_format($next_year, 'Y');

another way I found to only use 1 object is

$today = new DateTime();
echo date_format($today->sub(new DateInterval('P1Y')), 'Y').' '.date_format($today->add(new DateInterval('P1Y')), 'Y').' '.date_format($today->add(new DateInterval('P1Y')), 'Y');

but that will become very confusing. Can someone tell me a better way to do this using DateTime()? As I will need something similar for months ?

6 Answers
Related