When a week has two numbers
Published: 1/4/2013 2:28:40 PM
The other day I was getting indications that one of my applications was behaving strangely. Without getting too techinical about it, it seemed like the application had lost data. Losing data is never good, so I had to find and fix the issue quickly.
An integral part of the application is week numbers. When the user logs on, the current week number is calculated by passing the date of the last Monday (unless its Monday today, then today's date are passed in) to the Calendar.GetWeekOfYear() method. The application then assumes that the week number is the same for the rest of the days of the week, which is a valid assumption according to week rules in Sweden (which are based on the ISO 8601 standard).
This logic should work fine on most situations, but given that the problem occurred on the week of New Year's Eve I suspected that it could be related to the week calculation. In my code I have an extension method that calculates the week number like this:
public static int GetWeekNumber(this DateTime date)
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
Calendar calendar = dfi.Calendar;
return calendar.GetWeekOfYear(date, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);
}
By passing in some values to the method I could immediately confirm that the method was calculating differently than expected: passing in December 31 2012 (Monday) would return week number 53 while January 1 2013 (Tuesday) would return week number 1. The correct behavior according to ISO 8601 would be to return week number 1 in both cases.
It turns out, according to some of the comments on the MSDN documentation for Calendar.GetWeekOfYear, that the method are not ISO 8601 compatible. Bummer. However, a work-around (complete with source code) can be found here. After implementing the work-around my application started to work as expected.