Week of Year C# Datetime
Asked Answered
F

6

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?

Farly answered 11/4, 2012 at 8:49 Comment(2)
try with this cal.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday)Sciatic
@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.Sixtyfour
K
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

Kensell answered 11/4, 2012 at 8:51 Comment(0)
G
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.

Goalie answered 3/1, 2013 at 3:48 Comment(0)
S
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.

Sixtyfour answered 11/4, 2012 at 8:57 Comment(0)
R
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 );
Racy answered 11/4, 2012 at 10:1 Comment(0)
P
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.

Phyllis answered 11/4, 2012 at 8:52 Comment(0)
I
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.

Inept answered 11/4, 2012 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.