週番号から日付を計算する 質問する

週番号から日付を計算する 質問する

週の最初の日の日付 (ヨーロッパでは月曜日) を取得する簡単な方法を知っている人はいませんか。年と週番号はわかっていますか? これを C# で実行します。

ベストアンサー1

@RobinAndersson による修正を適用しても、@HenkHolterman による解決策に問題がありました。

ISO 8601 標準について調べると、この問題はうまく解決します。月曜日ではなく、最初の木曜日をターゲットとして使用します。以下のコードは、2009 年の第 53 週でも機能します。

public static DateTime FirstDateOfWeekISO8601(int year, int weekOfYear)
{
    DateTime jan1 = new DateTime(year, 1, 1);
    int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek;

    // Use first Thursday in January to get first week of the year as
    // it will never be in Week 52/53
    DateTime firstThursday = jan1.AddDays(daysOffset);
    var cal = CultureInfo.CurrentCulture.Calendar;
    int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);

    var weekNum = weekOfYear;
    // As we're adding days to a date in Week 1,
    // we need to subtract 1 in order to get the right date for week #1
    if (firstWeek == 1)
    {
        weekNum -= 1;
    }

    // Using the first Thursday as starting week ensures that we are starting in the right year
    // then we add number of weeks multiplied with days
    var result = firstThursday.AddDays(weekNum * 7);

    // Subtract 3 days from Thursday to get Monday, which is the first weekday in ISO8601
    return result.AddDays(-3);
}       

おすすめ記事