Home >Backend Development >C++ >How to Calculate the First Day of a Week Given Year and Week Number Using ISO 8601?
Accurate date calculation based on ISO 8601 standard
Finding the first day of a specific week based on year and week number may seem simple, but becomes complicated if you use the ISO 8601 standard, which states that the first day of the week is Monday in Europe, but in the standard It's Thursday.
In order to calculate the date accurately, we first determine the first Thursday of the year. This ensures that we are always in the correct year, regardless of whether the first week of the year spans two calendar years.
If the first week of the year is week 1, subtract 1 from the given week number to account for the difference in starting dates.
Finally, we multiply the week number by 7 days and add it to the first Thursday to get the first day of the specified week. However, to comply with the ISO 8601 definition, we will subtract 3 days from the resulting Thursday to obtain Monday, which is the first day in the standard.
The following is an example of implementing ISO 8601 conventions in C# code:
<code class="language-csharp">public static DateTime FirstDateOfWeekISO8601(int year, int weekOfYear) { DateTime jan1 = new DateTime(year, 1, 1); int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek; // 使用一月份的第一个星期四获取一年的第一周 DateTime firstThursday = jan1.AddDays(daysOffset); var cal = CultureInfo.CurrentCulture.Calendar; int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); var weekNum = weekOfYear; // 由于我们正在向第 1 周的日期添加天数, // 因此我们需要减去 1 才能获得第 1 周的正确日期 if (firstWeek == 1) { weekNum -= 1; } // 使用第一个星期四作为起始周确保我们从正确的年份开始 // 然后我们将周数乘以天数的结果相加 var result = firstThursday.AddDays(weekNum * 7); // 从星期四减去 3 天以获得星期一,这是 ISO8601 中的第一天 return result.AddDays(-3); }</code>
Using this method, you can accurately calculate the first day of the week based on the year and week number, ensuring compliance with ISO 8601 standards.
The above is the detailed content of How to Calculate the First Day of a Week Given Year and Week Number Using ISO 8601?. For more information, please follow other related articles on the PHP Chinese website!