Search code examples
c#methods

Trying to get the number of weeks as displayed in a calendar in a month


I simply want my method to return the number of weeks in a given month as displayed in calendars in rows. I seem to encounter a problem when I reach June 2025. This contains 30 days spread out over 6 rows in a calendar. See Outlook, MudBlazor Date picker or any other calendar for reference.

private static int GetWeeksInMonth(DateTime date)
{
    Calendar calendar = CultureInfo.CurrentCulture.Calendar;
    DateTime firstDay = new(date.Year, date.Month, 1);
    int days = DateTime.DaysInMonth(date.Year, date.Month);
    DateTime lastDay = new(date.Year, date.Month, days);
              
    int firstWeek = calendar.GetWeekOfYear(firstDay, CalendarWeekRule.FirstDay, firstDay.DayOfWeek);
    int lastWeek = calendar.GetWeekOfYear(lastDay, CalendarWeekRule.FirstDay, lastDay.DayOfWeek);

    return (lastWeek - firstWeek) + 1;
}

My method keeps returning 5 and not 6. firstWeek is 23 and lastWeek is 27. This method seems to work for any other month of the year.


Solution

  • You are missusing GetWeekOfYear parameters, the last one should be same value for both calls, e.g. DayOfWeek.Monday.

    The correct value of firstWeek is 22, not 23 (fiddle).