Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Go to top

DateTime extension method to give Week number

, 19 Jul 2011
Rate this:
Please Sign up or sign in to vote.
There certainly is a direct method in .NET to obtain the ISO week number.It is even quite simple; it is, however, buggy - as ISO week numbering "always" has been at MSFT since VB 3.0 and Access Basic (of Access 2.0) and through all versions up to and including VBA of Office 2010. It is a big...

There certainly is a direct method in .NET to obtain the ISO week number.

It is even quite simple; it is, however, buggy - as ISO week numbering "always" has been at MSFT since VB 3.0 and Access Basic (of Access 2.0) and through all versions up to and including VBA of Office 2010. It is a big question why it hasn't been resolved in .NET. Fortunately, a tiny test for week 53 (study in-line comment please) will get it right.

/// <summary>
/// Gets the week number according to the ISO 8601 standard of this instance.
/// <para>This is the corrected value from Calendar.GetWeekOfYear(this, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday)</para>
/// </summary>
/// <param name="currentDate">The current date<
/// <returns>Returns the ISO 8601 week number of this instance.</returns>

public static int WeekIso8601(this DateTime currentDate)
{
    CultureInfo cultureInfo = CultureInfo.InvariantCulture;
    Calendar calendar = cultureInfo.Calendar;
    CalendarWeekRule calenderWeekRule = CalendarWeekRule.FirstFourDayWeek;
    DayOfWeek firstDayOfWeek = DayOfWeek.Monday;
            
    int weekNumber = 
      calendar.GetWeekOfYear(currentDate, 
        calenderWeekRule, firstDayOfWeek);
    if (weekNumber.Equals(_maxIso8601WeekNumber))
    {
        // The week number appears to be 53. 
        // If so, the week number of the next week must be 1.
        // Obtain the week number of the next week and check if this is 1.
        int weekNumberNext = 
          calendar.GetWeekOfYear(currentDate.AddWeeks(1), 
            calenderWeekRule, firstDayOfWeek);
        if (!weekNumberNext.Equals(_minIso8601WeekNumber))
        {
            // The next week has week number 2.
            // Thus, the current week number is not 53 but 1.
            weekNumber = _minIso8601WeekNumber;
        }
    }
    return weekNumber;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Gustav Brock
Architect Cactus Data ApS
Denmark Denmark
No Biography provided
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140905.1 | Last Updated 19 Jul 2011
Article Copyright 2011 by Gustav Brock
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid