How many work (non-weekend) days between now and then?

As a developer, it’s not often you get to use a do { … } while(); loop, so, while you do (see what I did there?), it’s time for a celebration!

I needed to find the number of work days between two dates (now and then), I’d seen many, many much longer functions on the web and decided there must be an easier way to do it. So, this is it.

<?

/**
 * @desc    Return how many non-weekend days between two dates
 * @param   timestamp $toDate
 * @param   timestamp $fromDate
 * @author  Mike Pearce <mike@mikepearce.net>
 * @return  integer
 **/
function howManyWorkDays($toDate, $fromDate = FALSE)
{
    // The time RIGHT NOWs
    if (!$fromDate) $fromDate = time();
    $numberOfDays = 0;
    
    // Is it a timestamp? Maybe.
    if (
        is_int($toDate) AND 
        $toDate > $fromDate
    )
    {
        // While the current time is less than the time in the future
        do {
            // Add 1 day to the current time
            $fromDate = strtotime("+1 day", $fromDate);
            
            // If that day is a WEEKDAY, increment.
            if (date("N", $fromDate) < 6)
            {
                $numberOfDays++;
            }
        } while($fromDate < $toDate);
    }
    // Number of work days between now and then
    return $numberOfDays;
    
}

echo "Workdays between until Christmas Day: ". howManyWorkDays(strtotime("25th December"));
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s