Counting regular working days in a given period of time

后端 未结 8 423
庸人自扰
庸人自扰 2021-01-12 05:38

need some help. I need to count regular working days for a given date period, for example, in our country, we have 5 regular working days monday to friday, then in code i ne

8条回答
  •  -上瘾入骨i
    2021-01-12 06:11

    I wrote a type extender to allow me to add (or subtract) weekdays to a given date. Maybe this will help you. Works great, so please vote for my post if this helped you.

        /// 
        /// Adds weekdays to date
        /// 
        /// DateTime to add to
        /// Number of weekdays to add
        /// DateTime
        public static DateTime AddWeekdays(this DateTime value, int weekdays)
        {
            int direction = Math.Sign(weekdays);
            int initialDayOfWeek = Convert.ToInt32(value.DayOfWeek);
    
            //---------------------------------------------------------------------------
            // if the day is a weekend, shift to the next weekday before calculating
            if ((value.DayOfWeek == DayOfWeek.Sunday && direction < 0)
                || (value.DayOfWeek == DayOfWeek.Saturday && direction > 0))
            {
                value = value.AddDays(direction * 2);
                weekdays += (direction * -1); // adjust days to add by one
            }
            else if ((value.DayOfWeek == DayOfWeek.Sunday && direction > 0)
                || (value.DayOfWeek == DayOfWeek.Saturday && direction < 0))
            {
                value = value.AddDays(direction);
                weekdays += (direction * -1); // adjust days to add by one
            }
            //---------------------------------------------------------------------------
    
            int weeksBase = Math.Abs(weekdays / 5);
            int addDays = Math.Abs(weekdays % 5);
    
            int totalDays = (weeksBase * 7) + addDays;
            DateTime result = value.AddDays(totalDays * direction);
    
            //---------------------------------------------------------------------------
            // if the result is a weekend, shift to the next weekday
            if ((result.DayOfWeek == DayOfWeek.Sunday && direction > 0)
                || (result.DayOfWeek == DayOfWeek.Saturday && direction < 0))
            {
                result = result.AddDays(direction);
            }
            else if ((result.DayOfWeek == DayOfWeek.Sunday && direction < 0)
                || (result.DayOfWeek == DayOfWeek.Saturday && direction > 0))
            {
                result = result.AddDays(direction * 2);
            }
            //---------------------------------------------------------------------------
    
            return result;
        }
    

提交回复
热议问题