Calculate week of month in .NET

There is no built in way to do this but here is an extension method that should do the job for you:

static class DateTimeExtensions {
    static GregorianCalendar _gc = new GregorianCalendar();
    public static int GetWeekOfMonth(this DateTime time) {
        DateTime first = new DateTime(time.Year, time.Month, 1);
        return time.GetWeekOfYear() - first.GetWeekOfYear() + 1;
    }

    static int GetWeekOfYear(this DateTime time) {
        return _gc.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
    }
}

Usage:

DateTime time = new DateTime(2010, 1, 25);
Console.WriteLine(time.GetWeekOfMonth());

Output:

5

You can alter GetWeekOfYear according to your needs.

Leave a Comment