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
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With