Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get this day last year in PHP?

So I'm currently using Carbon for getting dates, times and comparisons. I can do subYear() easily enough to get this date last year. Now I need something to get the exact same day at the same time last year, e.g Wednesday of the second week of April.

I'd expect to have to do something that works out the current day of the week, e.g 3, and the current week of the year, then get the same value last year.

Just thought I'd check if there's anything available that already does this in Carbon or other PHP tools? Thanks

like image 504
sturrockad Avatar asked May 05 '15 17:05

sturrockad


People also ask

How do I get this year in PHP?

To get the current year using PHP's date function, you can pass in the “Y” format character like so: //Getting the current year using //PHP's date function. $year = date("Y"); echo $year; The example above will print out the full 4-digit representation of the current year.

How can I get previous date in PHP?

To get yesterday's date in PHP simply use the DateTime class and instantiate it with the constructor parameter 'yesterday' Then you can format the DateTime object with the format method.


1 Answers

I think DateTime::setISODate() is exactly what you need:

$today = new \DateTime();

$year  = (int) $today->format('Y');
$week  = (int) $today->format('W'); // Week of the year
$day   = (int) $today->format('w'); // Day of the week (0 = sunday)

$sameDayLastYear = new \DateTime();
$sameDayLastYear->setISODate($year - 1, $week, $day);

echo "Today: ".$today->format('Y-m-d (l, W)').PHP_EOL;
echo "Same week and day last year: ".$sameDayLastYear->format('Y-m-d (l, W)').PHP_EOL;

Output (for today, 2015-05-05):

Today: 2015-05-05 (Tuesday, 19)
Same week and day last year: 2014-05-06 (Tuesday, 19)
like image 133
jeromegamez Avatar answered Sep 20 '22 23:09

jeromegamez