Been toying with this for a bit and haven't really come up with a good solution, so thought I'd check out here
I need to calculate the number of week days between 2 timestamps. The timestamps will be a date with either a midnight or noon time (whole day or half day) and used to figure out how much vacation a member of staff is taking
Short of looping through every day between the 2 dates and counting them, is there a better way?
[solved]How do I get the number of weekdays between 2 stamps
Moderator: General Moderators
[solved]How do I get the number of weekdays between 2 stamps
Last edited by Kadanis on Fri Oct 03, 2008 10:48 am, edited 1 time in total.
Re: How do I get the number of weekdays between 2 stamps?
Calculate the number of days, then divide that by 7 for the number of weeks, then multiply that by 5. Then correct for the start or end date falling on a weekend.
Re: How do I get the number of weekdays between 2 stamps?
i think that someone has submitted a function getDaysBetween on the strtotime page at http://www.php.net
Re: How do I get the number of weekdays between 2 stamps?
Thanks for the responses guys, ended up with a loop as onions suggestion was too precise, i.e giving 0.23453 of a day etc.
Thought I'd just post my final solution in case anyone ever needs it in the future
Thought I'd just post my final solution in case anyone ever needs it in the future
Code: Select all
<?php
/**
* Calculates the number of week days between 2 set dates.
*
* Expects Unix Epoch time stamps as the arguments.
*
* @param integer $startDate
* @param integer $endDate
* @return integer
*
* @example echo weekDayDifference(1222815600, 1223420399);
*
*/
function weekDayDifference($startDate, $endDate){
//count days off between 2 dates
$daysOff = round(abs($endDate - $startDate) / 86400);
//remove weekend days
$date = $startDate;
for ($i = 0; $i < $daysOff; $i ++){
$day = date('D', $date);
if (strtolower($day) == 'sat' || strtolower($day) == 'sun'){
$daysOff--;
}
$date += 86400;
}
return $daysOff;
}
?>