1

How would I get the number of weekday hours between two dates? (There's a lot of business days calculations, but doesn't seem to be much on weekday hours - not business/opening hours, just hours that aren't weekends).

This is my stab at it - is there a better way?

void Main()
{
    // Works
    DateTime start = new DateTime(2013,6,15,0,0,0); // Saturday
    DateTime end = new DateTime(2013,6,17,10,0,0);  // Monday   

    // Result = 10 (OK)
    GetBusinessHours(start, end).Dump();        

    // Bugs
    start = new DateTime(2013,6,14,0,0,0); // Friday
    end = new DateTime(2013,6,15,0,0,0); // Saturday

    // Result = 0 (Bug) - should be 24
    GetBusinessHours(start, end).Dump();        
}

public double GetBusinessHours(DateTime start, DateTime end)
{
    double result = (end - start).TotalHours;

    int weekendDays = Enumerable.Range(0, 1 + end.Subtract(start).Days).Select(offset => start.AddDays(offset)).Count(d => d.DayOfWeek == DayOfWeek.Sunday || d.DayOfWeek == DayOfWeek.Saturday);       

    double weekendDeltaHours = 0;
    if (start.DayOfWeek == DayOfWeek.Saturday ||
        start.DayOfWeek == DayOfWeek.Sunday)
    {           
        weekendDays--;
        weekendDeltaHours = start.Date.AddDays(1).Subtract(start).TotalHours;
    }
    else if (end.DayOfWeek == DayOfWeek.Saturday ||
            end.DayOfWeek == DayOfWeek.Sunday)
    {
        weekendDeltaHours = (end - end.Date).TotalHours;
    }

    result = result - (weekendDays * 24) - weekendDeltaHours;           
    return result;
}

(Props to Ani for Enumerable.Range trick).

Community
  • 1
  • 1
PeterX
  • 2,713
  • 3
  • 32
  • 42

1 Answers1

2

Not that this will be the most efficient method, it will work for what you require.

var end = DateTime.Now;
var start = end.AddDays(-100);
var weekend = new[] { DayOfWeek.Saturday, DayOfWeek.Sunday };

var count = Enumerable.Range(0, Convert.ToInt32(end.Subtract(start).TotalHours))
     .Count(offset => !weekend.Contains(start.AddHours(offset).DayOfWeek));

It might be worth putting a check that the number of hours isn't too big for an int. However this would mean a date range of > 245,000 years!

Oliver
  • 8,794
  • 2
  • 40
  • 60