Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

last year, this year, next year with php DateTime

Tags:

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

like image 210
anatak Avatar asked Jan 02 '14 06:01

anatak


1 Answers

Depending upon your version of PHP (>= 5.4), you could tidy it up a bit like this:-

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

See it working.

A more readable and concise option may be to use \DateTimeImmutable.

$today = new DateTimeImmutable();
$one_year = new DateInterval('P1Y');

$last_year = $today->sub($one_year);
$next_year = $today->add($one_year);
echo $last_year->format('Y').' '.$today->format('Y').' '.$next_year->format('Y');

See it working.

Other than that, this all looks fine. Worry about optimisation when it is needed.

like image 76
vascowhite Avatar answered Oct 13 '22 11:10

vascowhite