tags:

views:

1842

answers:

2

I'm creating a UI that allows the user the select a date range, and tick or un-tick the days of the week that apply within the date range.

The date range controls are DateTimePickers, and the Days of the Week are CheckBoxes

Here's a mock-up of the UI:

From Date: (dtpDateFrom)
To Date: (dtpDateTo)

[y] Monday, [n] Tuesday, [y] Wednesday, (etc)

What's the best way to show a total count the number of days, based not only on the date range, but the ticked (or selected) days of the week?

Is looping through the date range my only option?

+2  A: 

Looping through wouldn't be your only option - you could perform subtraction to figure out the total number of days, and subtract one for each of your "skipped" dates every week range in between that contains one of those days. By the time you figure out whether a day lands on one of the partial weeks at the beginning or end of the range and add #weeks * skipped days in a week, your code will be more complicated than it would be if just counted, but if you're expecting to have huge date ranges, it might perform better.

If I were you, I'd write the simple looping option and rewrite it if it turned out that profiling revealed it to be a bottleneck.

Blair Conrad
I think I'll follow your advice and do the simple loop option first, then I'll probably have a stab at ravenspoint's algorithm :o)
Andrew
Here are some timings for the simple loop option: 1/Jan/0001 - 31/Dec/2000: counting [730453] days took [00:00:02.1875000], 1/Jan/0001 - 31/Dec/9999: [3651662] days took [00:00:11.2812500]. Conclusion? The simple loop is easily fast enough on my target hardware :o)
Andrew
How long is "00:00:02.1875000". Does it mean just over 2 seconds? If so, that seems horribly slow to me.
ravenspoint
Correct - just over 2 seconds for every day in ~2000 years
Andrew
+4  A: 

Here's how I would approach it:

  • Find day of week (dow) of first and last date
  • Move first day forward to same dow as last. Store number of days moved that are to be included
  • Calculate number of weeks between first and last
  • Calculate number of included days in a week * number of weeks + included days moved

As pseudo code:

 moved = start + end_dow - start_dow
 extras = count included days between start and moved
 weeks = ( end - moved ) / 7
 days = days_of_week_included * weeks + extras

This will take constant time, no matter how far apart the start and end days.

The details of implementing this algorithm depend on what language and libraries you are using. Where possible, I use C++ plus boost::date_time for this sort of thing.

ravenspoint