Counting regular working days in a given period of time

后端 未结 8 578
庸人自扰
庸人自扰 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条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 05:59

    You could do it with a time line helper class - this class also allows for other intervals:

    public class TimeLine
    {
        public static IEnumerable CreateTimeLine(DateTime start, TimeSpan interval) {
            return TimeLine.CreateTimeLine(start, interval, DateTime.MaxValue);
        }
    
        public static IEnumerable CreateTimeLine(DateTime start, TimeSpan interval, DateTime end) {
            var currentVal = start;
            var endVal = end.Subtract(interval);
    
            do {
                currentVal = currentVal.Add(interval);
                yield return currentVal;
            } while (currentVal <= endVal);
        }
    }
    

    To solve your problem you can do the following:

    var workingDays = TimeLine.CreateTimeLine(DateTime.Now.Date, TimeSpan.FromDays(1), DateTime.Now.Date.AddDays(30))
                              .Where(x => x.DayOfWeek != DayOfWeek.Saturday && x.DayOfWeek != DayOfWeek.Sunday);
    var noOfWorkingDays = workingDays.Count();
    

    This time line class can be used for any continuous time line of any interval.

提交回复
热议问题