[英]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 . 我正在创建PHP函数,该函数将以两种格式返回两个日期之间的差额: 2个月,3周,6天,3小时 。 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 .
我尝试使用PHP DateTime类,但是它仅返回Months,Days和Hours,并且我找不到计算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. 现在,我需要$ Difference [“ Weeks”]也包含在返回数据中。
EDIT: I know I can divide Days with 7 and get weeks, but this does not result right. 编辑:我知道我可以将Days除以7并得到几周,但是结果不正确。 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.
例如: 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.