Count number of Mondays in a given date range

后端 未结 15 1299
南旧
南旧 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 10:11

    It's fun to look at different algorithm's for calculating day of week, and @Gabe Hollombe's pointing to WP on the subject was a great idea (and I remember implementing Zeller's Congruence in COBOL about twenty years ago), but it was rather along the line of handing someone a blueprint of a clock when all they asked what time it was.

    In C#:

        private int CountMondays(DateTime startDate, DateTime endDate)
        {
            int mondayCount = 0;
    
            for (DateTime dt = startDate; dt < endDate; dt = dt.AddDays(1.0))
            {
                if (dt.DayOfWeek == DayOfWeek.Monday)
                {
                    mondayCount++;
                }
            }
    
            return mondayCount;
        }
    

    This of course does not evaluate the end date for "Mondayness", so if this was desired, make the for loop evaluate

    dt < endDate.AddDays(1.0)
    

提交回复
热议问题