Munam Yousuf
Munam Yousuf

Reputation: 547

Get Week number from a given date when week start on Sunday

How to get the correct week number of the year from a given date when my first day of week is Sunday.

For example:

6 May 2018 - 12 May 2018 is week 18

13 May 2018 - 19 May 2018 is week 19

I'm trying the following extension method but unable to achieve the desired result. It's giving week 19 and 20 where I expect week 18 and 19 respectively.

public static int GetWeekOfYear(this DateTime date)
{
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(
      date, 
      CalendarWeekRule.FirstFourDayWeek, 
      DayOfWeek.Sunday);
}

Upvotes: 1

Views: 1516

Answers (2)

DirtyBit
DirtyBit

Reputation: 16772

CalendarWeekRule Enumeration: Defines different rules for determining the first week of the year.

Previously what you were using:

CalendarWeekRule.FirstFourDayWeek

which needed to be replaced with:

CalendarWeekRule.FirstFullWeek

Because:

enter image description here

Code Snippet:

public static void Main()
{
    var week_test = Convert.ToDateTime("05/06/2018");
    var week_test2 = Convert.ToDateTime("05/13/2018");
    List<DateTime> weekList = new List<DateTime>();
    weekList.Add(week_test);
    weekList.Add(week_test2);
    CultureInfo ciCurr = CultureInfo.CurrentCulture;
  foreach(var week in weekList)
  {
    int weekNum = ciCurr.Calendar.GetWeekOfYear(week, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday);
    Console.WriteLine(weekNum);
  }
}

Output:

enter image description here

Demo:

dotNetFiddle

Upvotes: 1

Lucifer
Lucifer

Reputation: 1594

you need to change the argument for method

CultureInfo.InvariantCulture.Calendar.GetWeekOfYear()

CalendarWeekRule.FirstFourDayWeek -> CalendarWeekRule.FirstFullWeek

as per Document for FirstFullWeek - Indicates that the first week of the year begins on the first occurrence of the designated first day of the week on or after the first day of the year.

like this

public static int GetWeekOfYear(DateTime date)
{
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday);
}

Upvotes: 1

Related Questions