1

我如何获得两个日期之间的工作日小时数?(有很多工作日计算,但工作日时间似乎并不多 - 不是营业/营业时间,只是不是周末的时间)。

这是我的尝试-有更好的方法吗?

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;
}

(向Ani提供 Enumerable.Range 技巧的道具)。

4

1 回答 1

2

并不是说这将是最有效的方法,它可以满足您的需求。

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));

可能值得检查一下小时数对于int. 然而,这将意味着 > 245,000 年的日期范围!

于 2013-06-12T07:43:33.770 回答