Álvaro García
Álvaro García

Reputation: 19356

how to calculate the number of the week in a year?

I would like to calculte the number of the week in a year. I see this post

In this post the acepted answer use this code:

public static int GetIso8601WeekOfYear(DateTime time)
{
    // Seriously cheat.  If its Monday, Tuesday or Wednesday, then it'll 
    // be the same week# as whatever Thursday, Friday or Saturday are,
    // and we always get those right
    DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
    if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
    {
        time = time.AddDays(3);
    }

    // Return the week of our adjusted day
    return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

However I see a problem. The number of the week is repeated if the last day of a month is in Sunday.

For example, the last day of March of 2013 year is in sunday. This week is the number 13th, is correct. But in April, how C# use always 6 weeks in a month to calculate the number of week, the first week of april has not any day of april, because all the days belong to march because the last day of the week is 30th March. So C# says that the first week of april is th 15th week, but this is incorrect, it has to be 14th.

So I would like to know if there are any way to calculate the number of a week in a right way.

EDIT:

I mean this:

In march, the last week is this:

25 26 27 28 29 30 31

This is the 13th, is correct.

In april, the first week is:

1 2 3 4 5 6 7

And this week is calculated as 15th.

So if I see the march calendar the last week is calculated as 13th and if I see the april calendar the last week of march is caluclated as 14th. This is incorrect.

SOLUTION:

DateTime dtCalendar = Calendar.DisplayDate;
int gridRow = (int)GetValue(Grid.RowProperty);

// Return the week of our adjusted day
int wueekNumber= System.Globalization.CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(dtCalendar, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);

if (dtCalendar.DayOfWeek == DayOfWeek.Monday)
{
    gridRow = gridRow - 1;
}

Text = (weekNumbe r+ gridRow - 1).ToString();  

Thanks.

Upvotes: 1

Views: 1108

Answers (1)

user2480047
user2480047

Reputation:

The problem is that you are using the wrong CalendarWeekRule. To get the result you want you should use FirstDay. I have seen various codes in internet saying that you should use FirstFourDayWeek but, after some testing, I realised that the "right one" is FirstDay. I have tested it with your example and it delivers the right result: 14th week.

int targetYear = 2013;
DateTime targetDate = new DateTime(targetYear, 4, 1);
int week = System.Globalization.CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(targetDate, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Monday);

Upvotes: 1

Related Questions