### Get current week number from Date C#

How can I get the current week number from the date using C# (dot net core)?

Imports:

using System;

using System.Collections.Generic;

using System.Linq;

Solution #1: Considering Sunday as the first day of the week.

public static int GetCurrentWeek(DateTime dt)

{

// Sunday as first day of week

DateTime firstOfMonth = new DateTime(dt.Year, dt.Month, 1);

return ((dt.Day - 1 + (int)firstOfMonth.DayOfWeek)) / 7 + 1;

}

Solution #2: Considering Monday as the first day of the week.

public static int GetCurrentWeek(DateTime dt)

{

// Monday as first day of week

DateTime firstOfMonth = new DateTime(dt.Year, dt.Month, 1);

int dayOfWeek = (int)(firstOfMonth.DayOfWeek) - 1;

if(dayOfWeek < 0) dayOfWeek = 6;

return (dt.Day - 1 + dayOfWeek) / 7 + 1;

}

Method Usage:

Console.WriteLine (GetCurrentWeek(new DateTime(2022, 06,27)));

What we have to consider monday as first day?. Do we have to +- 2 in that case.

ReplyDeletePlease see updated answer

Delete