简体   繁体   English

PHP计算日期之间的周数,并舍入到最近的一周

[英]PHP Calculate Number of Weeks Between Dates and Round up to Nearest Week

I am trying to figure out how to calculate the number of weeks between to dates for billing. 我试图弄清楚如何计算开票日期之间的周数。 Billing is weekly so 1+ days = a week and 8+ days = 2 weeks and so on.. 计费是每周一次,因此1+天=一周,而8 +天= 2周,依此类推。

So far I have my code working out the number of weeks but it doesnt seems to round up to the nearest week even if it is only a day over (This is what I need) 到目前为止,我的代码可以算出星期数,但是即使只有一天,它似乎也不舍入到最近的一周(这是我需要的)

I hope I have explained it correctly, this is what I have so far. 我希望我已经正确解释了,这是我到目前为止的内容。

$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";

Does anyone know how I could ammend my code to do what I need. 有谁知道我可以如何修改我的代码以完成所需的工作。 In the code I pasted it gives 4 weeks as the answer but It should be five as it is at least 1 day more than 4 weeks. 在我粘贴的代码中,它给出了4周的答案,但是应该为5周,因为它至少比4周多1天。

Thanks so much in advance 提前非常感谢

您需要ceil而不是round

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

It's far easier working with DateTime objects. 使用DateTime对象要容易得多。

Assuming that the difference is less than a year: 假设差异少于一年:

$startDate = new DateTime($strtDate);
$interval = $startDate->diff(new DateTime($endDate));

echo ceil($interval->days / 7);

otherwise (if more than a year) 否则(如果超过一年)

$startDate = new DateTime($strtDate);
$interval = $startDate->diff(new DateTime($endDate));

echo ceil(($interval->y * 365 + $interval->days) / 7);

although that doesn't take leap years into account 尽管这并没有考虑leap年

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM