Calculate week of month in .NET

There is no direct built-in way to do this, but it can be done quite easily. Here is an extension method which can be used to easily get the year-based week number of a date:

public static int GetWeekNumber(this DateTime date)
{
    return GetWeekNumber(date, CultureInfo.CurrentCulture);
}

public static int GetWeekNumber(this DateTime date, CultureInfo culture)
{
    return culture.Calendar.GetWeekOfYear(date,
        culture.DateTimeFormat.CalendarWeekRule,
        culture.DateTimeFormat.FirstDayOfWeek);
}

We can then use that to calculate the month-based week number, kind of like Jason shows. A culture friendly version could look something like this:

public static int GetWeekNumberOfMonth(this DateTime date)
{
    return GetWeekNumberOfMonth(date, CultureInfo.CurrentCulture);
}

public static int GetWeekNumberOfMonth(this DateTime date, CultureInfo culture)
{
    return date.GetWeekNumber(culture)
         - new DateTime(date.Year, date.Month, 1).GetWeekNumber(culture)
         + 1; // Or skip +1 if you want the first week to be 0.
}

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.

Tags:

.Net

Datetime