anatak anatak - 7 months ago 42
PHP Question

last year, this year, next year with php DateTime

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
? As I will need something similar for months ?


May be you can also limit the call of new DateInterval('P1Y') by creating one object and using it for all three calculations?

$interval = new DateInterval('P1Y');

$dateTime = new DateTime();
$lastYear = $dateTime->sub($interval)->format('Y');

$dateTime = new DateTime();
$nextYear = $dateTime->add($interval)->format('Y');

$dateTime = new DateTime();
$thisYear = $dateTime->format('Y');

echo $lastYear . ' ' . $thisYear . ' ' . $nextYear;

and by breaking the single string into multiple commands always helps me in reducing confusions.