Wednesday, February 01, 2006
Note to self: how to calculate week numbers in .NET
Today was certainly not the first time that I had to calculate week numbers for a DateTime in C#. I know that the problem is rather complex, but that the .NET framework knows how to do it. Still, every time I need it, I have to use Google to find the way to do it and to my amazement, the first 3 or 4 solutions I find are always hand-coded, bad solutions.
These handcoders never take into account that the week number calculation is done differently in different countries. Some countries have weeks start on monday (which seems at least biblically correct) and others on sunday (which seems to be more like the Torah). Then: which week is the first week? Is it the week of January 1st? Is it the first week that falls mostly in the new year? Or the first that falls fully in the new year? Not only does .NET a good job in the calculation, it also knows what rules apply in which culture.
So for once and for all, this is the way:
Comments:
Links to this post:
<< Home
That raises another question: how do you find the year to go with that number? E.g. 2008-12-30 is in week 1 of 2009.
Post a Comment
Links to this post:
<< Home



