PHP计算日期之间的周数和最近一周的周数

时间:2016-03-10 21:58:35

标签: php date rounding

我想弄清楚如何计算截至日期之间的周数。结算是每周一次,所以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天。

非常感谢

2 个答案:

答案 0 :(得分:2)

您希望ceil代替round

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

答案 1 :(得分: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);

虽然这不考虑闰年