Page 1 of 1
[solved]How do I get the number of weekdays between 2 stamps
Posted: Mon Sep 29, 2008 3:29 am
by Kadanis
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?
Re: How do I get the number of weekdays between 2 stamps?
Posted: Mon Sep 29, 2008 3:33 am
by onion2k
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?
Posted: Mon Sep 29, 2008 3:42 am
by deejay
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?
Posted: Fri Oct 03, 2008 10:21 am
by Kadanis
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
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;
}
?>