nikname
nikname

Reputation: 161

Date difference in days no matter year

How could I calculate date difference between two dates without paying attention to year?

So for example if I have $first = '20/08/2019' and $second = '10/08/2020', the function should return 10, even though the $second date is one year ahead of $first?

Upvotes: 0

Views: 41

Answers (2)

nikname
nikname

Reputation: 161

I have found a way to do this. Just get the bigger year (in my case I know it will always be for the $first date) and recreate $second date using that year:

$first = new \DateTime('10/08/2020');
$first_year = $first->format('Y');
$second = new \DateTime('20/08/2019'); 
$second_without_year = $second->format('m-d');
$second_modified = new \DateTime($first_year.'-'.$second_without_year);
    
$first->diff($second_modified)->format("%R%a");

Upvotes: 1

Vishnu Vijaykumar
Vishnu Vijaykumar

Reputation: 450

By ignoring the year, I suppose we include leap years as well. In that case, the below code might work:

$first = date_create('20-08-2019');
$second = date_create('10-08-2020');
$interval = date_diff($first, $second);
$diff = abs($interval->format("%R%a"));
if($diff>365){
  $diff = intval($diff/365);
}

To ignore the leap year days, subtract the number of leap years between the years from $diff

Upvotes: 0

Related Questions