Count number of Mondays in a given date range

后端 未结 15 1306
南旧
南旧 2020-11-28 09:35

Given a date range, I need to know how many Mondays (or Tuesdays, Wednesdays, etc) are in that range.

I am currently working in C#.

15条回答
  •  误落风尘
    2020-11-28 09:59

    A bit Modified Code is here works and Tested by me

            private int CountDays(DayOfWeek day, DateTime startDate, DateTime endDate)
            {
                int dayCount = 0;
    
                for (DateTime dt = startDate; dt < endDate; dt = dt.AddDays(1.0))
                {
                    if (dt.DayOfWeek == day)
                    {
                        dayCount++;
                    }
                }
    
                return dayCount;
            }
    

    Example:

    int Days = CountDays(DayOfWeek.Friday, Convert.ToDateTime("2019-07-04"), 
                 Convert.ToDateTime("2019-07-27")).ToString();
    

提交回复
热议问题