[solved]How do I get the number of weekdays between 2 stamps

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Kadanis
Forum Contributor
Posts: 180
Joined: Tue Jun 20, 2006 8:55 am
Location: Dorset, UK
Contact:

[solved]How do I get the number of weekdays between 2 stamps

Post 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?
Last edited by Kadanis on Fri Oct 03, 2008 10:48 am, edited 1 time in total.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: How do I get the number of weekdays between 2 stamps?

Post 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.
User avatar
deejay
Forum Contributor
Posts: 201
Joined: Wed Jan 22, 2003 3:33 am
Location: Cornwall

Re: How do I get the number of weekdays between 2 stamps?

Post by deejay »

i think that someone has submitted a function getDaysBetween on the strtotime page at http://www.php.net
User avatar
Kadanis
Forum Contributor
Posts: 180
Joined: Tue Jun 20, 2006 8:55 am
Location: Dorset, UK
Contact:

Re: How do I get the number of weekdays between 2 stamps?

Post 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;
}
?>
 
Post Reply