Leon Meijer's Weblog

About my personal life, technology and business/work related...
posts - 128, comments - 334, trackbacks - 0

Determining the week number of 31/12/2008, because .NET is wrong

If you call the .NET method GetWeekOfYear on a Calendar object with the appropriate week rules (For The Netherlands/EU: CalendarWeekRule=FirstFourDayWeek and FirstDayOfWeek=Monday) for the date 31-dec-2008 you'll get 53. This is incorrect because the year 2008 has only 52 weeks. The correct answer should be 1, because January 1 till 4 form the first four day week, making the three days before (29, 30, 31 dec) also part of week 1. I googled this issue and found more people with the same problem. I found a working answer on http://www.eggheadcafe.com/software/aspnet/33093322/number-of-weeks-in-year.aspx :
public static int WeekNumber(DateTime fromDate)
{
    // Get jan 1st of the year
    DateTime startOfYear = fromDate.AddDays(-fromDate.Day + 1).AddMonths(-fromDate.Month + 1);
    // Get dec 31st of the year
    DateTime endOfYear = startOfYear.AddYears(1).AddDays(-1);
    // ISO 8601 weeks start with Monday
    // The first week of a year includes the first Thursday, i.e. at least 4 days
    // DayOfWeek returns 0 for Sunday up to 6 for Saturday
    int[] iso8601Correction = { 6, 7, 8, 9, 10, 4, 5 };
    int nds = fromDate.Subtract(startOfYear).Days + iso8601Correction[(int)startOfYear.DayOfWeek];
    int wk = nds / 7;
    switch (wk)
    {
        case 0:
            // Return weeknumber of dec 31st of the previous year
            return WeekNumber(startOfYear.AddDays(-1));
        case 53:
            // If dec 31st falls before thursday it is week 01 of next year
            if (endOfYear.DayOfWeek < DayOfWeek.Thursday)
                return 1;
                    else
                        return wk;
        default: return wk;
    }
}

 

Hope this helps,

Print | posted on Monday, January 05, 2009 1:48 PM |

Powered by: