Skip to content

May 23, 2008

Number of Weeks In A Month

So I am working on a .NET web app that needs to calculate how many weeks there are in a month. I have come upon some solutions but I put one together that I like better than the rest…

public int Weeks(int year, int month, DayOfWeek firstDayOfWeek)
{

CultureInfo ciCulture = new CultureInfo(“en-US”);
System.Globalization.Calendar cal = ciCulture.Calendar;

return cal.GetWeekOfYear(DateTime(year, month, DateTime.DaysInMonth(year, month)), ciCulture.DateTimeFormat.CalendarWeekRule, firstDayOfWeek) – cal.GetWeekOfYear(DateTime(year, month, 1), ciCulture.DateTimeFormat.CalendarWeekRule, firstDayOfWeek);
}

This lets the .NET Framework do the thinking for me, and it is Globalization ready. Anywho the logic is::

Find the week number for the end of the month, subtract the week number for the start of the month… bam! Number of weeks.

The method is dependent on what day of the week a new week starts. So if your week starts on a Monday throw that it’s way.

Should this be in the framework? Probably …

PS:

using System.Globalization; //<-- ADD THAT;

Read more from Random Rants

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments