Week numbers in C#
To get the current ISO 8601 week number in C#, use the following code snippet:
using System.Globalization;
// ISOWeek was introduced in .NET Core 3.0
int week = ISOWeek.GetWeekOfYear(DateTime.Now);
* Ensure your system or application regional settings are set to follow ISO 8601 standards (weeks start on Monday) if the output varies.
Step-by-Step Instructions
- Add using System.Globalization; at the top of the file.
- Call ISOWeek.GetWeekOfYear(DateTime.Now) (.NET Core 3.0 and later).
- For the ISO year use ISOWeek.GetYear(DateTime.Now).
Good to Know
Before ISOWeek existed, the common Calendar.GetWeekOfYear(..., CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday) approach had a known edge-case bug in .NET Framework that misnumbers a few days around New Year. Prefer ISOWeek on modern runtimes.