2

Currently the last years date is off by 2 days. In other words, if I run a report today 8/14/2016 the date last year on this day(sunday) should be 8/16/2015 and it's showing 8/14/2015.

The code that's currently in place is

$date = new DateTime($current_time); 
$day = $date->format('l');          
$date->sub(new DateInterval('P1Y')); // back 1 year
$date->modify('next ' . $day); 
$date->modify('next ' . $day);  

Since P1Y doesn't take into account leap year and a few other things after reading about it, I read adding what I added below fixes that problem but it doesn't fix it.

$date = new DateTime($current_time);
    $i = new DateInterval('P1Y');
    $now = new DateTime;
    while ($date >= $now) {
      echo $date->format('c') . PHP_EOL;
      $date = $date->sub($i);
    }

This code gives me the same 8/14/2015.

Can someone tell me what I'm doing wrong?

Jad
  • 163
  • 1
  • 12
  • 4
    Since you bring up leap years, what is the expected behaviour if the code were to run on February 29th 2016? Should it give the nonexistant February 29th 2015, or "round" to March 1st 2015? – Niet the Dark Absol Aug 14 '16 at 18:39
  • @NiettheDarkAbsol "Today doesn't exist. Come back tomorrow." :P – Siguza Aug 14 '16 at 18:40
  • Isn't today's date 14/08/2016? Or are you in the east, like Australia? But then you should get 15/08/2015 after the subtraction. – trincot Aug 14 '16 at 19:14
  • Actually I'm wrong it should be 8/16/2015. What I'm saying is today is Sunday, 2016.08.14 and last year it was Sunday, 2016.08.16. So off by 2 days. – Jad Aug 14 '16 at 19:33
  • Possible duplicate of [Date minus 1 year?](http://stackoverflow.com/questions/1990321/date-minus-1-year) – j08691 Aug 14 '16 at 19:45
  • No but I wish that was the problem. – Jad Aug 14 '16 at 20:29
  • Your definition of 1 year is wrong - think about your birthday - it's always on the same date - and has different weekdays over the years. But this differs for different types of calandars - the Gregorian is sun based - while others like the islamic are moon based. – PowerStat Jul 25 '19 at 07:46

0 Answers0