Search code examples
phpdatetimedate-difference

PHP DateTime Difference (Hours, Days, Weeks, Months)


I am creating PHP function that will return difference between two dates in a format: 2 Months, 3 Weeks, 6 Days, 3 Hours. I have tried to use PHP DateTime class, but it returns only Months, Days and Hours and I can not find a way to calculate Weeks.

This is my function:

public function DateTimeDifference($FromDate, $ToDate) {
  $FromDate = new DateTime($FromDate);
  $ToDate   = new DateTime($ToDate);
  $Interval = $FromDate->diff($ToDate);

  $Difference["Hours"] = $Interval->h;
  $Difference["Days"] = $Interval->d;
  $Difference["Months"] = $Interval->m;

  return $Difference;
}

Now, I need $Difference["Weeks"] also included in return data.

EDIT: I know I can divide Days with 7 and get weeks, but this does not result right. For example: 2 Months, 14 Days, 3 Hours - When I divide 14 days with 7 I will get this: 2 Months, 2 Weeks, 14 Days, 3 Hours and now this is not same period.


Solution

  • public function DateTimeDifference($FromDate, $ToDate) {
      $FromDate = new DateTime($FromDate);
      $ToDate   = new DateTime($ToDate);
      $Interval = $FromDate->diff($ToDate);
    
      $Difference["Hours"] = $Interval->h;
      $Difference["Weeks"] = floor($Interval->d/7);
      $Difference["Days"] = $Interval->d % 7;
      $Difference["Months"] = $Interval->m;
    
      return $Difference;
    }