Week of Year C# Datetime

Nicolas picture Nicolas · Apr 11, 2012 · Viewed 22.1k times · Source

I have following code to get the weeknumber of the year given in the DateTime object Time

    public static int WeeksInYear(DateTime date)
    {
        GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
        return cal.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
    }

I give the function the date 1/1/2012 which should return week 1, but it is returning week 52. And I can't seem to figure out why. Anyone have an idea why?

Answer

KingCronus picture KingCronus · Apr 11, 2012

The algorithm is doing exactly what you have instructed it to do. You have the CalanderWeekRule set to FirstFourDayWeek. The 1st of January 2012 was not part of the first four day week, so you have instructed the calander to start counting from January 2nd.

Calculate date from week number