Counting regular working days in a given period of time

后端 未结 8 421
庸人自扰
庸人自扰 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:53

    One-liner!

    int workingDays = Enumerable.Range(0, Convert.ToInt32(endDate.Subtract(startDate).TotalDays)).Select(i=>new [] { DayOfWeek.Saturday, DayOfWeek.Sunday }.Contains(startDate.AddDays(i).DayOfWeek) ? 0 : 1).Sum();
    

    Or more efficient:

    DayOfWeek currDay = startDate.DayOfWeek;
    int nonWorkingDays = 0;
    
    foreach(var i in Enumerable.Range(0, Convert.ToInt32(endDate.Subtract(startDate).TotalDays)))
    {
         if(currDay == DayOfWeek.Sunday || currDay == DayOfWeek.Saturday) 
              nonWorkingDays++;
         if((int)++currDay > 6) currDay = (DayOfWeek)0;
    }
    

提交回复
热议问题