Calculating a date's week number is a frequent programming task, but surprisingly complex. Consider 2012-12-31: many methods incorrectly return 53, while intuitively, it should be week 1.
The Problem: Calendar Variations
The core issue lies in calendar inconsistencies. Standard .NET calendars allow weeks to cross year boundaries, unlike the ISO 8601 standard, which keeps weeks within a single year.
The ISO 8601 Solution
To ensure accuracy, using the ISO 8601 standard is essential. The following GetIso8601WeekOfYear
method, compliant with this standard, correctly identifies 2012-12-31 as week 1.
<code class="language-csharp">public static int GetIso8601WeekOfYear(DateTime time) { DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time); if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) { time = time.AddDays(3); } return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); }</code>
This method guarantees week number calculation according to ISO 8601, offering consistent and logical results.
The above is the detailed content of How to Accurately Determine the Week Number of a Date?. For more information, please follow other related articles on the PHP Chinese website!