Monday, February 20, 2012

Finding the week number from a date–ISO 8601

I previously wrote about how to find the first day or date given a week number and how to get that working correctly.

Going the other way is in theory easier as you can use functions from .Net itself.

public static int GetWeekNumber(this DateTime date)
{
    var currentCulture = CultureInfo.CurrentCulture;
    return currentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}

Except there is a bug in .Net which will return the wrong week for some boundary dates around the end of December and the beginning of January.

The fix is equal to that of my previous post, use the Thursday of the week of your date and it will work.

public static int GetWeekNumber(this DateTime date)
{
    int daysToAdd = date.DayOfWeek != DayOfWeek.Sunday ? DayOfWeek.Thursday - date.DayOfWeek : (int)DayOfWeek.Thursday - 7;
    date = date.AddDays(daysToAdd);
    var currentCulture = CultureInfo.CurrentCulture;
    return currentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}