Determine the difference between two DateTimes, only counting opening hours

前端 未结 6 2126
梦毁少年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:32

    try this

    namespace ConsoleApplication1
    {
    class Program
    {
        static void Main(string[] args)
        {
            var date1 = new DateTime(2010, 10, 12, 12, 00, 00);
            var date2 = new DateTime(2010, 10, 14, 15, 00, 00);
    
            var hr1 = ((date1.Hour > 9) && (date1.Hour < 17)) ? 17 - date1.Hour : 0;
            var hr2 = ((date2.Hour > 9) && (date2.Hour < 17)) ? 17 - date2.Hour : 0;
    
            var middleHours = ((date2.Date -  date1.Date).Days -1) * 8 ;
    
            Console.WriteLine(hr1+hr2+ middleHours);
            Console.ReadKey();
    
        }
    }
    

    }

    I have try it, and it is working :)

提交回复
热议问题