Home >Backend Development >C++ >How to Calculate a Date from a Week Number in C# Using ISO 8601?

How to Calculate a Date from a Week Number in C# Using ISO 8601?

Linda Hamilton
Linda HamiltonOriginal
2025-01-14 13:12:43728browse

How to Calculate a Date from a Week Number in C# Using ISO 8601?

Calculate date based on week number

Many programming tasks require calculating the corresponding date based on a given week number. In C#, this can be achieved using the ISO 8601 standard.

The ISO 8601 standard starts the first week on the first Thursday of each year instead of Monday. Taking advantage of this convention, the following code accurately determines the first day of a specific week in a specified year:

<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;
    if (firstWeek == 1)
    {
        weekNum -= 1;
    }

    var result = firstThursday.AddDays(weekNum * 7);
    return result.AddDays(-3);
}</code>

This code solves the case where the first Thursday is not the first week of the year. By subtracting three days from the first Thursday, it correctly returns Monday as the first day of the specified week according to the ISO 8601 standard.

The above is the detailed content of How to Calculate a Date from a Week Number in C# Using ISO 8601?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn