[C#] 주 번호에서 날짜 계산

누구나 주중 첫날 (유럽의 월요일)을 쉽게 얻을 수있는 방법을 알고 있습니다. 연도와 주 번호를 알고 있습니까? 나는 C #에서 이것을 할 것입니다.



답변

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


답변

나는 Henk Holterman이 제공하는 솔루션을 좋아합니다. 그러나 좀 더 독립적 인 문화를 유지하려면 현재 문화에 대한 첫 번째 요일을 가져와야합니다 (항상 월요일은 아닙니다).

using System.Globalization;

static DateTime FirstDateOfWeek(int year, int weekOfYear)
{
  DateTime jan1 = new DateTime(year, 1, 1);

  int daysOffset = (int)CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek - (int)jan1.DayOfWeek;

  DateTime firstMonday = jan1.AddDays(daysOffset);

  int firstWeek = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(jan1, CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule, CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek);

  if (firstWeek <= 1)
  {
    weekOfYear -= 1;
  }

  return firstMonday.AddDays(weekOfYear * 7);
}


답변

업데이트 : .NET Core 3.0 및 .NET Standard 2.1은이 유형과 함께 제공됩니다.

좋은 소식! .NET Core에 추가 되는 풀 요청System.Globalization.ISOWeek 이 병합되었으며 현재 3.0 릴리스로 예정되어 있습니다. 바라지 않는 미래에 다른 .NET 플랫폼으로 전파되기를 바랍니다.

ISOWeek.ToDateTime(int year, int week, DayOfWeek dayOfWeek)방법을 사용하여 이를 계산할 수 있어야합니다 .

소스 코드는 여기에서 찾을 수 있습니다 .


답변

가장 쉬운 방법은 해당 연도의 첫 번째 월요일을 찾은 다음 관련 주 수를 추가하는 것입니다. 샘플 코드는 다음과 같습니다. 그것은 1부터 시작하는 주 번호를 가정합니다.

using System;

class Test
{
    static void Main()
    {
        // Show the third Tuesday in 2009. Should be January 20th
        Console.WriteLine(YearWeekDayToDateTime(2009, DayOfWeek.Tuesday, 3));
    }

    static DateTime YearWeekDayToDateTime(int year, DayOfWeek day, int week)
    {
        DateTime startOfYear = new DateTime (year, 1, 1);

        // The +7 and %7 stuff is to avoid negative numbers etc.
        int daysToFirstCorrectDay = (((int)day - (int)startOfYear.DayOfWeek) + 7) % 7;

        return startOfYear.AddDays(7 * (week-1) + daysToFirstCorrectDay);
    }
}


답변

개인적으로 나는 문화 정보를 이용하여 요일을 얻고 문화의 첫 요일로 넘어갑니다. 올바르게 설명하고 있는지 잘 모르겠습니다. 예를 들어 보겠습니다.

    public DateTime GetFirstDayOfWeek(int year, int weekNumber)
    {
        return GetFirstDayOfWeek(year, weekNumber, Application.CurrentCulture);
    }

    public DateTime GetFirstDayOfWeek(int year, int weekNumber,
        System.Globalization.CultureInfo culture)
    {
        System.Globalization.Calendar calendar = culture.Calendar;
        DateTime firstOfYear = new DateTime(year, 1, 1, calendar);
        DateTime targetDay = calendar.AddWeeks(firstOfYear, weekNumber);
        DayOfWeek firstDayOfWeek = culture.DateTimeFormat.FirstDayOfWeek;

        while (targetDay.DayOfWeek != firstDayOfWeek)
        {
            targetDay = targetDay.AddDays(-1);
        }

        return targetDay;
    }


답변

Fluent DateTime 사용 http://fluentdatetime.codeplex.com/

        var year = 2009;
        var firstDayOfYear = new DateTime(year, 1, 1);
        var firstMonday = firstDayOfYear.Next(DayOfWeek.Monday);
        var weeksDateTime = 12.Weeks().Since(firstMonday);


답변

스웨덴 에서 사용되는 ISO 8601 : 1988에 따르면 , 첫 번째주는 새해에 최소 4 일이 지난 주입니다.

따라서 주가 월요일에 시작되면 첫 번째 목요일은 첫 주 안에 있습니다. 그로부터 DateAdd 또는 DateDiff를 사용할 수 있습니다.