Get week of month C#

Enkhay picture Enkhay · Apr 14, 2014 · Viewed 17.5k times · Source

I want to find a date are now on week number with c# desktop Application.

I've been looking on google, but none that fit my needs.

How do I get a week in a month as the example below?

Example:

I want January 6, 2014 = the first week of January

January 30, 2014 = fourth week of January

but 1 February 2014 = week 4 in January

and 3 February 2014 was the first week in February

Answer

Ulugbek Umirov picture Ulugbek Umirov · Apr 14, 2014

Here is the method:

static int GetWeekNumberOfMonth(DateTime date)
{
    date = date.Date;
    DateTime firstMonthDay = new DateTime(date.Year, date.Month, 1);
    DateTime firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
    if (firstMonthMonday > date)
    {
        firstMonthDay = firstMonthDay.AddMonths(-1);
        firstMonthMonday = firstMonthDay.AddDays((DayOfWeek.Monday + 7 - firstMonthDay.DayOfWeek) % 7);
    }
    return (date - firstMonthMonday).Days / 7 + 1;
}

Test:

Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 1, 6)));  // 1
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 1, 30))); // 4
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 2, 1)));  // 4
Console.WriteLine(GetWeekNumberOfMonth(new DateTime(2014, 2, 3)));  // 1