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 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流