Soutenez Time.now : Rejoignez notre Plan Premium pour une expérience sans publicité ! Soutenez-nous : Passez Premium sans pub !

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.

Instructions étape par étape

  1. Add using System.Globalization; at the top of the file.
  2. Call ISOWeek.GetWeekOfYear(DateTime.Now) (.NET Core 3.0 and later).
  3. For the ISO year use ISOWeek.GetYear(DateTime.Now).

Bon à savoir

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.