aticatac aticatac - 1 year ago 218
C# Question

Calculate date from week number

Anyone know an easy way to get the date of the first day in the week (monday here europe). I know the year and the week number? I'm going to do this in C#.

Thanks in advance.

Answer Source

I had issues with the solution by @HenkHolterman even with the fix by @RobinAndersson.

Reading up on the ISO 8601 standard resolves the issue nicely. Use the first Thursday as the target and not Monday. The code below will work for Week 53 of 2009 as well.

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download