SYSK 284: Calculating WeekOfYear in C# Using 1 Line of Code Without Referencing Microsoft.VisualBasic.dll
What week number (1 through 53) does January 6th 2008 belong to using the standard US calendar with Sunday being the first day of the week? If you answered ‘1’, that’s incorrect – since Jan. 01, 2008 starts on a Tuesday, Jan. 06th falls on Sunday and thus is the start of the second week.
As you can see, calculating it as
dt.DayOfYear / 7 + (dt.DayOfYear % 7 > 0 ? 1 : 0)
would yield an incorrect result.
So, what’s the easiest way to get the correct result? Here is how I do it:
System.Threading.Thread.CurrentThread.CurrentCulture.Calendar.GetWeekOfYear(dt, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday)
Comments
Anonymous
February 09, 2007
P.S. google for: Zeller congruenceAnonymous
February 09, 2007
I believe the MSDN documentation (http://msdn2.microsoft.com/en-gb/library/system.globalization.calendarweekrule.aspx) alludes to a way of getting GetWeekOfYear to result in ISO 8601 compliant week numbers. From what I've seen this does not comply with 8601. If 8601 week numbers are what you're looking for, see http://blogs.msdn.com/shawnste/archive/2006/01/24/517178.aspx