Reputation: 33
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..
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.
Thanks so much in advance
Upvotes: 3
Views: 2770
Reputation: 653
You want ceil
instead of round
.
ceil(abs(strtotime("2016-05-20") - strtotime("2016-05-12")) / 60 / 60 / 24 / 7);
Upvotes: 5
Reputation: 212452
It's far easier working with DateTime objects.
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
Upvotes: 4