Skip to content
Advertisement

Find date diff output as each year

Now I use date_diff() to find diff of date

public function getDateDiff($date1,$date2){
    $date1 = date_create('2019-12-29');
    $date2 = date_create('2020-01-05');
    $diff = date_diff($date1,$date2); // Diff is 7 days
}

I need output as array something like

$date1 = date_create('2019-12-29');
$date2 = date_create('2020-01-05');
$diff_array = getDateDiff($date1,$date2);
$diff_array['2019'] = 2; // 29 Dec 2019 - 31 Dec 2019 
$diff_array['2020'] = 5; // 1 Jan 2020 - 5 Jan 2020

$date1 = date_create('2020-10-10');
$date2 = date_create('2020-10-20');  
$diff_array = getDateDiff($date1,$date2);  
$diff_array['2020'] = 10; // 10 Jan 2020 - 20 Jan 2020

Advertisement

Answer

Ciao, you can do something like:

  1. Get year from each date;
  2. If year are equal then $diff_array[$date1->format("Y")] = $diff_array.format("d");
  3. Else take last day of $date1’s year, calculate difference and then $diff_array[$date1->format("Y")] = $diff_array.format("d");
  4. Take the first day of $date2’s year, calculate difference and then $diff_array[$date2->format("Y")] = $diff_array.format("d");
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement