The online home of John Pollard

Counting Weekdays Between Two Dates

Been slower going now I’m in a contract again - need to get paid!

However I’ve finally got around to fixing the algorithm I was using to calculate the number of weekdays between two dates.

I knew the original one I’d found via a web search was wrong, as I could see the results were wrong when calculating how many days left in my contract. I wrote a failing unit test to capture the issue, and then set about using my brain instead of taking other people’s code for granted.

The algorithm

As ever the code is the most succinct way of describing the solution, but as a basic outline the steps are these:

  1. Adjust the start and end datetimes to be the start of the day
  2. If the start date is a Saturday or Sunday, move it forward to the next Monday (SAdj)
  3. If the end date is a Saturday or Sunday, move it back to the previous Friday (EAdj)
  4. Calculate the days between the adjusted start and end dates (EAdj - SAdj).Days = AdjTotalDays
  5. Calculate the full weeks between the adjusted start and end dates (AdjTotalDays / 7) = AdjWeeks
  6. The tricky bit - Get the day of week (using Apple’s numbering of 1 == Sunday…7 == Saturday) for EAdjDayOfWeek and SAdjDayOfWeek
  7. Calculate EAdjDayOfWeek - SAdjDayOfWeek = DaysDifference
  8. If DaysDifference < 0, then DaysDifference += 5 (this is to adjust how the week wraps around the weekend)
  9. Finally, return (AdjWeeks * 5) + DaysDifference

I think this is correct, and all my unit tests show the model now behaves as I expected, so I think we’re all good!

Next steps

I’m ready to let people start beta-testing the app, but because I’m using a beta version of Xcode I can’t use TestFlight and the iTunes Store.

However this might be a good time to check out Twitter’s dev support including Crashlytics and their Beta distribution support.

Previous posts in the series

The code for the project is also available on GitHub