Count number of Mondays in a given date range

后端 未结 15 1301
南旧
南旧 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:44

    Here's some pseudocode:

    DifferenceInDays(Start, End) / 7   // Integer division discarding remainder
    + 1 if DayOfWeek(Start) <= DayImLookingFor
    + 1 if DayOfWeek(End)   >= DayImLookingFor
    - 1
    

    Where DifferenceInDays returns End - Start in days, and DayOfWeek returns the day of the week as an integer. It doesn't really matter what mapping DayOfWeek uses, as long as it is increasing and matches up with DayImLookingFor.

    Note that this algorithm assumes the date range is inclusive. If End should not be part of the range, you'll have to adjust the algorithm slightly.

    Translating to C# is left as an exercise for the reader.

提交回复
热议问题