Derik Whittaker



How to determine the number of ‘Wednesday’s’ in a given date range (Fun Code)

Today I ‘fun need’ which I don’t ever recall coming across before and I thought I would share my results.

I needed to find both the number of Wednesdays (or any day for instance) and the date for each instance for a given date range.  What I came up w/ was as follows (the code below is LINQPad C# but is 100% valid).

var startDate = new DateTime(2012, 10, 1);
var endDate = new DateTime(2012, 10, 31);
var totalDays = (int)endDate.Subtract(startDate).TotalDays + 1; // need to offset the math

var totalDates = Enumerable.Range(1, totalDays).Select(n => startDate.AddDays(n));

var days = totalDates.Where (x => x.DayOfWeek == DayOfWeek.Wednesday );

days.Count ().Dump();

I thought this was fun and pretty simple.  I am sure there are a thousand ways to do this, but i like this one.

Till next time,

Posted 10-19-2012 12:47 PM by Derik Whittaker
Filed under: ,



sergiopereira wrote re: How to determine the number of ‘Wednesday’s’ in a given date range (Fun Code)
on 10-31-2012 10:13 AM

You know you can't throw a coding challenge on programmers like that and don't expect for people telling you're doing it wrong, right? ;)

I found you solution interesting but the use of LINQ overkill when modulo arithmetic would suffice. Here's my crack at it (I have not unit tested it thoroughly but it seems to work):

int GetNumberOfOccurrences(DayOfWeek dow, DateTime startDate, DateTime endDate) {

DateTime nextDowStart = startDate.AddDays((7 + dow - startDate.DayOfWeek)%7);

DateTime prevDowEnd = endDate.AddDays(-(7 + endDate.DayOfWeek - dow)%7);

return 1 + (prevDowEnd - nextDowStart).Days/7;


Mike Minutillo wrote re: How to determine the number of ‘Wednesday’s’ in a given date range (Fun Code)
on 11-05-2012 3:25 AM

This is my pretty but ultimately inefficient solution. As a plus I get the Generate() method out of it which is useful in all sorts of areas. LINQ ALL THE THINGS!

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)