5

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

Machavity
  • 30,841
  • 27
  • 92
  • 100
sturrockad
  • 4,460
  • 2
  • 19
  • 19

4 Answers4

7

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)
jeromegamez
  • 3,348
  • 1
  • 23
  • 36
3

For anyone else using Carbon you can do a similar solution to splash's and just have:

Carbon::now()->subWeeks(52)

gives 2014-05-07 14:11:48

sturrockad
  • 4,460
  • 2
  • 19
  • 19
2

Make it easier :)

echo date('Y-m-d (l, W)', strtotime("-52 week"));

Edit: I forgot to write output: :)

2014-05-07 (Wednesday, 19)

UPDATE2:

There is a problem with jeromegamez' code. A year can contain 52 or 53 weeks. Taking 3 January of 2016:

$today = new \DateTime();
$today->setDate ( 2016 , 1 , 3 );

$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;

result is:

Today: 2016-01-03 (Sunday, 53) 
Same week and day last year: 2015-12-27 (Sunday, 52)

only five days instead of years :)

splash58
  • 26,043
  • 3
  • 22
  • 34
  • Yes I've been looking into this and trying to decide whether we want to let the date value to move on longer years so will see – sturrockad May 08 '15 at 09:47
  • It not so far as you think. Set date `$today->setDate ( 2016 , 1 , 3 );` You receive `Today: 2016-01-03 (Sunday, 53) Same week and day last year: 2015-12-27 (Sunday, 52)`. only five days instead of years :) – splash58 May 08 '15 at 10:06
  • 1
    Look 52 weeks back seems better :) – splash58 May 08 '15 at 10:10
2

Something even easier <3

date('Y-m-d', strtotime('last year'))
user6363467
  • 124
  • 1
  • 10