c#确定特定时间内一段时间内的小时数

时间:2014-04-08 13:48:14

标签: c# .net timespan

我有一段时间的事件(例如2014年4月6日11:30到2014年4月8日10:15)我有办公室开放时间(例如星期一到星期五的9:00到17:00)。 / p>

我需要计算受事件影响的开放时间(小数)。

我能想出一种可以做到这一点的方法,但它似乎非常冗长和混乱所以想看看是否有人能想出一些优雅的东西?

由于 千电子伏

3 个答案:

答案 0 :(得分:2)

这是使用LINQ的简短易读的方法。请注意,它既没有充分测试也没有效率。但无论如何它也许有用:

DateTime incidentStart = new DateTime(2014, 04, 06, 11, 30, 0, 0, 0);
DateTime incidentEnd = new DateTime(2014, 04, 08, 10, 15, 0, 0, 0);
int minutes =  (int)(incidentEnd - incidentStart).TotalMinutes;
TimeSpan officeOpen = TimeSpan.FromHours(9);
TimeSpan officeClosed = TimeSpan.FromHours(17);
decimal numHours = Enumerable.Range(0, minutes)
    .Select(min => incidentStart.AddMinutes(min))
    .Where(dt => dt.DayOfWeek != DayOfWeek.Saturday && dt.DayOfWeek != DayOfWeek.Sunday 
       &&  dt.TimeOfDay >= officeOpen && dt.TimeOfDay < officeClosed)
    .GroupBy(dt => new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0, 0)) // round to hour
    .Count();

结果是11似乎是正确的,不是吗?

答案 1 :(得分:2)

这个答案准确到最接近的秒数。

DateTime startDate = new DateTime(2014, 04, 06, 11, 30, 0, 0, 0);
DateTime endDate = new DateTime(2014, 04, 08, 10, 15, 0, 0, 0);
TimeSpan StartOfDay = new TimeSpan(9, 0, 0);
TimeSpan EndOfDay = new TimeSpan(17, 0, 0);            
int secondCount= 0;

while ((endDate - startDate).Minutes >= 0)
{
    if (startDate.DayOfWeek >= DayOfWeek.Monday && startDate.DayOfWeek <= DayOfWeek.Friday)
        if (startDate.TimeOfDay > StartOfDay && startDate.TimeOfDay <= EndOfDay)                        
            secondCount++;
    startDate = startDate.AddSeconds(1);
}

Console.WriteLine("Total Hours and Minutes: " + new TimeSpan(0, 0, secondCount));

答案 2 :(得分:1)

非LINQ方法,也是Tim回答,未经测试。使用风险自负

var startDate = new DateTime(2014, 04, 06, 11, 30, 0, 0, 0);
var endDate = new DateTime(2014, 04, 08, 10, 15, 0, 0, 0);

var openStart = new DateTime(2014, 04, 08, 9, 0, 0);
var openEnd = new DateTime(2014, 04, 08, 17, 0, 0);;

var totalAffected = TimeSpan.Zero;
var checkDate = startDate;
while (checkDate < endDate)
{
    if (IsWorkDay(checkDate))
    {
        totalAffected = totalAffected.Add(openEnd.TimeOfDay - openStart.TimeOfDay);    
    }

    checkDate = checkDate.AddDays(1);
}

if (IsWorkDay(checkDate))
{
    if (endDate.TimeOfDay > openEnd.TimeOfDay)
    {
        totalAffected = totalAffected.Add(openEnd.TimeOfDay - openStart.TimeOfDay);
    }
    else
    {
        totalAffected = totalAffected.Add(endDate.TimeOfDay - openStart.TimeOfDay);
    }
}

double numberOfAffectedHours = totalAffected.TotalHours;

private bool IsWorkDay(DateTime day)
{
    return !(day.DayOfWeek == DayOfWeek.Saturday || day.DayOfWeek == DayOfWeek.Sunday);
}