The problem is not the number of days in a month, but how many weeks it covers.
February in a non-leap year will have 28 days, and if the first day of the month is Monday, February will be exactly 4 weeks.
However, if the first day of the month is Tuesday or any other day of the week, February will cover 5-week numbers.
A 31-day month can span 5 or 6 weeks in the same way. If the month starts on Monday, 31 days gives you 5-week numbers. If the month starts on Saturday or Sunday, it will cover 6 weeks.
Thus, the correct way to get this number is to find the week number on the first and last days of the month.
Change # 1 : here, how to calculate the number of weeks in a given month: Change # 2 : fixed bugs in the code
public static Int32 GetWeekForDateCurrentCulture(DateTime dt) { CultureInfo culture = Thread.CurrentThread.CurrentCulture; Calendar cal = culture.Calendar; return cal.GetWeekOfYear(dt, culture.DateTimeFormat.CalendarWeekRule, culture.DateTimeFormat.FirstDayOfWeek); } public static Int32 GetWeekSpanCountForMonth(DateTime dt) { DateTime firstDayInMonth = new DateTime(dt.Year, dt.Month, 1); DateTime lastDayInMonth = firstDayInMonth.AddMonths(1).AddDays(-1); return GetWeekForDateCurrentCulture(lastDayInMonth) - GetWeekForDateCurrentCulture(firstDayInMonth) + 1; }
Lasse Vågsæther Karlsen
source share