计算日期从周数日期

2023-09-02 11:29:36 作者:淡笑看过尘世。

任何人都知道一个简单的方法来获得的第一天的一周(星期一在这里欧洲)的日期。我知道这一年的周数?我要做到这一点在C#。

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#.

在此先感谢。

推荐答案

我有问题,即使与@RobinAndersson修复该解决方案通过@HenkHolterman。

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

读了ISO 8601标准很好地解决了问题。使用第一个星期四为目标,而不是周一。下面的code将工作周53 2009年也是如此。

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);
}