views:

3869

answers:

6

What's the easiest way to compute the amount of working days since a date? VB.NET preferred, but C# is okay.

And by "working days", I mean all days excluding Saturday and Sunday. If the algorithm can also take into account a list of specific 'exclusion' dates that shouldn't count as working days, that would be gravy.

Thanks in advance for the contributed genius.

+1  A: 

Here's a method for SQL Server. There's also a vbscript method on the page. Not exactly what you asked for, I know.

ranomore
+5  A: 

The easiest way is probably something like

DateTime start = new DateTime(2008, 10, 3);
DateTime end = new DateTime(2008, 12, 31);
int workingDays = 0;
while( start < end ) {
  if( start.DayOfWeek != DayOfWeek.Saturday
   && start.DayOfWeek != DayOfWeek.Sunday ) {
      workingDays++;
  }
  start = start.AddDays(1);
}

It may not be the most efficient but it does allow for the easy checking of a list of holidays.

Andrew Kennan
You mean checking of WEEKENDS. Not holidays. :D
ferventcoder
I imagine he meant that this particular algorithm would make it simple to check a list of holidays from within the loop if desired.
Nathan
+2  A: 

DateDiff along with a few other Date* functions are unique to VB.NET and often the subject of envy from C# developers. Not sure it'll be very helpful in this case, though.

Jeff Atwood
+1  A: 
Nathan
+1  A: 

in general (no code) -

  • subtract the dates to get the number of days
  • divide by 7 to get the number of weeks
  • subtract number of weeks times 2
  • count the number of holiday dates that fall with the date range
  • subtract that count

fiddle with the start/end dates so that they fall monday to monday, then add back the difference

[apologies for the no-code generalities, it's late]

[c.f. endDate.Subtract(startDate).TotalDays]

Steven A. Lowe
+5  A: 

This'll do what you want it to. It should be easy enough to convert to VB.NET, it's been too long for me to be able to do it though.

DateTime start = DateTime.Now;
DateTime end = start.AddDays(9);
IEnumerable<DateTime> holidays = new DateTime[0];

// basic data
int days = (int)(end - start).TotalDays;
int weeks = days / 7;

// check for a weekend in a partial week from start.
if (7- (days % 7) <= (int)start.DayOfWeek)
    days--;
if (7- (days % 7) <= (int)start.DayOfWeek)
    days--;

// lose the weekends
days -= weeks * 2;

foreach (DateTime dt in holidays)
{
    if (dt > start && dt < end)
        days--;
}
Matthew Scharley