Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get week of month C# [duplicate]

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

like image 757
Enkhay Avatar asked Apr 14 '14 12:04

Enkhay


1 Answers

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
like image 172
Ulugbek Umirov Avatar answered Oct 19 '22 08:10

Ulugbek Umirov