Counting Weekdays Between Two Dates09 Mar 2015
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.
As ever the code is the most succinct way of describing the solution, but as a basic outline the steps are these:
- Adjust the start and end datetimes to be the start of the day
- If the start date is a Saturday or Sunday, move it forward to the next Monday (SAdj)
- If the end date is a Saturday or Sunday, move it back to the previous Friday (EAdj)
- Calculate the days between the adjusted start and end dates (EAdj - SAdj).Days = AdjTotalDays
- Calculate the full weeks between the adjusted start and end dates (AdjTotalDays / 7) = AdjWeeks
- The tricky bit - Get the day of week (using Apple’s numbering of 1 == Sunday…7 == Saturday) for EAdjDayOfWeek and SAdjDayOfWeek
- Calculate EAdjDayOfWeek - SAdjDayOfWeek = DaysDifference
- If DaysDifference < 0, then DaysDifference += 5 (this is to adjust how the week wraps around the weekend)
- 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!
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
- Plan for DaysLeft App
- Baby Steps using Swift
- Porting UserSettings Code To Swift
- Basic UI in Swift
- Writing a Today Widget in Swift
- Adding a Custom Control
- Swift and Build Odds and Sods
- Animating Progress
The code for the project is also available on GitHub