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 周,因为它至少比 1 周多 4 天。

提前非常感谢

你想要ceil而不是round

ceil(abs(strtotime("2016-05-20") - strtotime("2016-05-12")) / 60 / 60 / 24 / 7);

使用 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);

虽然这没有考虑到闰年