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)