Hi. I'm Gabe. This was my semi-active blog from 2003-2005. It is currently unmaintained.
Please visit my professional site for something a little more recent.

OlderNewerJul 18, 2005

Date Formula

Working out a tricky formula is one of the things I like about web programming so much. Date calculations in particular can often be pretty tricky. I've got a set of "events" (projects actually) that span any number of days. The start date and end date of each is stored in a database. I need to know how many weekdays occur during the time span of each. Here is how I worked it out in PHP:


  1. Calculate the number of days between the two dates (including the start and end dates).

    $allDays = (strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24) + 1;
  2. Determine the day of the week for both the start date and the end date (numerical - 1 through 7).

    $startDOW = date('w', strtotime($startDate)) + 1;
  3. Calculate the number of weekdays found in full weeks

    $fullWeekdays = (floor($allDays / 7) * 5);
  4. And the tricky bit - calculate the remaining weekdays

    $modulusWeekdays = $endDOW - $startDOW + 1 + ($startDOW == 1 ? -1 : 0) + ($endDOW == 7 ? -1 : 0);

    if ($modulusWeekdays < 0) $modulusWeekdays += 5;
  5. Add the number of weekdays in full weeks to the remainder of weekdays and there's the answer. The number of weekdays that occur between any two dates.


UPDATE:

Here's a tool I've created that you can use to find the number of weekdays or weekends in a given time period: http://gabegrayum.com/tools/datecalc/
[Show all Posts]

Other Recent Posts:

B.C. Vacation [Jul 12, 2005]
ICal Bug Fixed [Jul 12, 2005]
The Spirit Of Disservice [May 31, 2005]
Yet Another Tiger Post [May 13, 2005]
Buying A Condo [Apr 24, 2005]