PHP 计算日期之间的周数并四舍五入到最近的一周
PHP Calculate Number of Weeks Between Dates and Round up to Nearest Week
我想知道如何计算结算日期之间的周数。按周计费,因此 1 天以上 = 一周,8 天以上 = 2 周,依此类推..
到目前为止,我已经用我的代码计算出周数,但它似乎没有四舍五入到最近的一周,即使它只结束了一天(这就是我需要的)
我希望我解释正确,这就是我目前所了解的。
$strtDate = '2016-03-08';
$endDate = '2016-04-07';
echo $strtDate, $endDate;
$startDateWeekCnt = round(floor( date('d',strtotime($strtDate)) / 7)) ;
$endDateWeekCnt = round(ceil( date('d',strtotime($endDate)) / 7)) ;
$datediff = strtotime(date('Y-m',strtotime($endDate))."-01") - strtotime(date('Y-m',strtotime($strtDate))."-01");
$totalnoOfWeek = round(floor($datediff/(60*60*24)) / 7) + $endDateWeekCnt - $startDateWeekCnt ;
echo $totalnoOfWeek ."\n";
有谁知道我可以如何修改我的代码来做我需要的事情。在我粘贴的代码中,它给出了 4 周的答案,但它应该是 5 周,因为它至少比 4 周多了 1 天。
非常感谢
使用 DateTime 对象要容易得多。
假设相差不到一年:
$startDate = new DateTime($strtDate);
$interval = $startDate->diff(new DateTime($endDate));
echo ceil($interval->days / 7);
否则(如果超过一年)
$startDate = new DateTime($strtDate);
$interval = $startDate->diff(new DateTime($endDate));
echo ceil(($interval->y * 365 + $interval->days) / 7);
尽管这没有考虑闰年
您想要 ceil
而不是 round
。
ceil(abs(strtotime("2016-05-20") - strtotime("2016-05-12")) / 60 / 60 / 24 / 7);
我想知道如何计算结算日期之间的周数。按周计费,因此 1 天以上 = 一周,8 天以上 = 2 周,依此类推..
到目前为止,我已经用我的代码计算出周数,但它似乎没有四舍五入到最近的一周,即使它只结束了一天(这就是我需要的)
我希望我解释正确,这就是我目前所了解的。
$strtDate = '2016-03-08';
$endDate = '2016-04-07';
echo $strtDate, $endDate;
$startDateWeekCnt = round(floor( date('d',strtotime($strtDate)) / 7)) ;
$endDateWeekCnt = round(ceil( date('d',strtotime($endDate)) / 7)) ;
$datediff = strtotime(date('Y-m',strtotime($endDate))."-01") - strtotime(date('Y-m',strtotime($strtDate))."-01");
$totalnoOfWeek = round(floor($datediff/(60*60*24)) / 7) + $endDateWeekCnt - $startDateWeekCnt ;
echo $totalnoOfWeek ."\n";
有谁知道我可以如何修改我的代码来做我需要的事情。在我粘贴的代码中,它给出了 4 周的答案,但它应该是 5 周,因为它至少比 4 周多了 1 天。
非常感谢
使用 DateTime 对象要容易得多。
假设相差不到一年:
$startDate = new DateTime($strtDate);
$interval = $startDate->diff(new DateTime($endDate));
echo ceil($interval->days / 7);
否则(如果超过一年)
$startDate = new DateTime($strtDate);
$interval = $startDate->diff(new DateTime($endDate));
echo ceil(($interval->y * 365 + $interval->days) / 7);
尽管这没有考虑闰年
您想要 ceil
而不是 round
。
ceil(abs(strtotime("2016-05-20") - strtotime("2016-05-12")) / 60 / 60 / 24 / 7);