Calculate the number of business days between two dates?

后端 未结 30 1227
悲&欢浪女
悲&欢浪女 2020-11-22 14:54

In C#, how can I calculate the number of business (or weekdays) days between two dates?

30条回答
  •  情话喂你
    2020-11-22 15:33

        int BusinessDayDifference(DateTime Date1, DateTime Date2)
        {
            int Sign = 1;
            if (Date2 > Date1)
            {
                Sign = -1;
                DateTime TempDate = Date1;
                Date1 = Date2;
                Date2 = TempDate;
            }
            int BusDayDiff = (int)(Date1.Date - Date2.Date).TotalDays;
            if (Date1.DayOfWeek == DayOfWeek.Saturday)
                BusDayDiff -= 1;
            if (Date2.DayOfWeek == DayOfWeek.Sunday)
                BusDayDiff -= 1;
            int Week1 = GetWeekNum(Date1);
            int Week2 = GetWeekNum(Date2);
            int WeekDiff = Week1 - Week2;
            BusDayDiff -= WeekDiff * 2;
            foreach (DateTime Holiday in Holidays)
                if (Date1 >= Holiday && Date2 <= Holiday)
                    BusDayDiff--;
            BusDayDiff *= Sign;
            return BusDayDiff;
        }
    
        private int GetWeekNum(DateTime Date)
        {
            return (int)(Date.AddDays(-(int)Date.DayOfWeek).Ticks / TimeSpan.TicksPerDay / 7);
        }
    

提交回复
热议问题