11

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Nicolas
  • 129
  • 1
  • 2
  • 5
  • try with this `cal.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday)` – Raghuveer Apr 11 '12 at 09:14
  • @RaghuveerGuthikonda: That would work only in this special case. E. g. 1/1/2013 might be a Saturday, it won't work. It's just the way calendar-weeks are calculated. The 1/1/2012 is in Week 52 and it is ought to be there. – basti Apr 12 '12 at 07:28

6 Answers6

9

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

Community
  • 1
  • 1
KingCronus
  • 4,509
  • 1
  • 24
  • 49
5
public static int WeeksInYear(DateTime date)
{
    GregorianCalendar cal = new GregorianCalendar(GregorianCalendarTypes.Localized);
    return cal.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Monday);

I think if change CalendarWeekRule.FirstFourDayWeek to CalendarWeekRule.FirstDay then this will work fine.

I changed this then its working fine.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Qmash
  • 51
  • 1
  • 1
1

The weeknumber was correctly calculated. You should have a read on how weeknumbers are actually calculated/counted (Wikipedia?!).

Attention: The built-in calculation of week-number-calculation is buggy. Microsoft describes the problem in the KnowledgeBase-Article 200299. It has problems with ISO-8601.

basti
  • 2,649
  • 3
  • 31
  • 46
1

You can use the class Week of the Time Period Library for .NET which supports supports the ISO 8601 week numbering:

TimeCalendar calendar = new TimeCalendar(
    new TimeCalendarConfig { YearWeekType = YearWeekType.Iso8601 } );
Week week = new Week( new DateTime( 2012, 01, 01 ), calendar );
Console.WriteLine( "week #: ", week.WeekOfYear );
0

I assume that because 1/1/2012 was a Sunday and GetWeekOfYear says it returns the week which includes the date, it's returning the last week of 2011 rather than the first week of 2012.

Have a look at the CalendarRule for clarification.

Nick
  • 25,026
  • 7
  • 51
  • 83
0

1/1/2012 it was sunday. I believe that's why you get 52, because it was last day of the last year week. For the 2nd of january you should get the right result.

lkurylo
  • 1,621
  • 33
  • 59