Determine the difference between two DateTimes, only counting opening hours

前端 未结 6 2128
梦毁少年i
梦毁少年i 2020-12-03 07:36

For our support software in C#, I need to determine the time span between two DateTimes, but I only want opening hours counted (i.e. weekdays from 09:00 to 17:00).

S

6条回答
  •  爱一瞬间的悲伤
    2020-12-03 08:40

    DateTime start = DateTime.Parse("15/02/2011 16:00");
    DateTime end = DateTime.Parse("16/02/2011 10:00");
    
    int count = 0;
    
    for (var i = start; i < end; i = i.AddHours(1))
    {
        if (i.DayOfWeek != DayOfWeek.Saturday && i.DayOfWeek != DayOfWeek.Sunday)
        {
            if (i.TimeOfDay.Hours >= 9 && i.TimeOfDay.Hours < 17)
            {
                count++;
            }
        }
    }
    
    Console.WriteLine(count);
    

提交回复
热议问题