PHP 日期时间差(小时、天、周、月)

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

我正在创建 PHP 函数,它将 return 两个日期之间的差异格式:2 个月、3 周、6 天、3 小时 .我尝试使用 PHP 日期时间 class,但它 return 只是月、日和小时,我找不到计算 周 [=26= 的方法].

这是我的功能:

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

现在,我需要 return 数据中也包含 $Difference["Weeks"]。

编辑:我知道我可以将天数除以 7 得到周数,但这并不正确。例如:2 个月,14 天,3 小时 - 当我将 14 天 除以 7 时,我将得到:2几个月,2 周,14 天,3 小时,现在不是同一时期。

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;
}
// this will only work from previous dates 
// difference between utc date time and custom date time

function FromUtcToCustomDateTimeDifference($ToDate)
{
    
    // Takes Two date time
    $UTC_DATE = new DateTime('now', new DateTimeZone('UTC'));
    $UTC_DATETIME = $UTC_DATE->format('Y-m-d H:i:s');
    
    // add your own date time 1
    $datetime1 = date_create(UTC_DATETIME);
    $datetime2 = date_create($ToDate);
   
    $Interval = date_diff($datetime1, $datetime2);

    // Count Number Of Days Difference
    
    $Day = $Interval->format('%a');
        
    if($Day > 1)
        {

            $Month = $Interval->format('%m');
            $Year = $Interval->format('%y');
            $Week = (int)($Interval->format('%a')/7);
            
            if($Year<1)
            {

                        if($Day <= 7)
                        {
                            return $Day > 1 ?  $Day.= " days ago" : $Day .= " day ago";

                        }

                        else if($Month<1)
                        {
                            
                        return $Week > 1 ?  $Week.= " weeks ago" : $Week .= " week ago";
                        }
                        
                        
                        return $Month > 1 ? $Month.= " months ago" : $Month .= " month ago";
            }
            else
            {
                return $Year > 1 ? $Year.= " years ago" : $Year .= " year ago";
                
            }

        
        }
        else
        {

            return "today";

        }

}