Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Week of Year C# Datetime

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?

like image 791
Nicolas Avatar asked Apr 11 '12 08:04

Nicolas


1 Answers

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

like image 124
KingCronus Avatar answered Sep 20 '22 14:09

KingCronus