doutao5419 2017-08-14 19:55
浏览 59
已采纳

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

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.

  • 写回答

1条回答 默认 最新

  • duanmei1894 2017-08-14 19:59
    关注
    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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大