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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动